What will be the output of the following code snippet using matplotlib?
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
plt.title('My Title')
plt.show()Note: plt.title() uses the pyplot interface acting on the current axes, ax.plot() is axes-level.
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6]) plt.title('My Title') plt.show()
plt.title() sets the title for the current axes, and ax is the current axes after plt.subplots() and ax.plot().
The ax.plot() draws the line on the axes ax, which is the current axes after plt.subplots(). plt.title() sets the title on the current axes. Therefore, the plot shows the line with the title 'My Title'.
Given the following code, which option shows the correct way to add a title to the axes-level plot?
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6]) # Add title here plt.show()
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6]) # Add title here plt.show()
Axes objects have a method to set the title directly.
The correct method to set the title on an axes object is ax.set_title(). Option D is invalid because ax.title() does not exist. Option D sets the title on the current axes but may not affect ax if multiple axes exist. Option D is invalid because fig.title() is not a valid method.
Consider the following code:
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset('iris')
sns.scatterplot(data=iris, x='sepal_length', y='sepal_width')
plt.show()How many axes are created and displayed by this code?
import seaborn as sns import matplotlib.pyplot as plt iris = sns.load_dataset('iris') sns.scatterplot(data=iris, x='sepal_length', y='sepal_width') plt.show()
Seaborn figure-level functions create a figure and one axes by default.
Seaborn's scatterplot is an axes-level function that creates one axes inside a figure. So, one axes is created and displayed.
Which statement best describes the difference between figure-level and axes-level methods in matplotlib and seaborn?
Think about what each method controls: the whole figure or just one plot area.
Figure-level methods create and manage the entire figure, which can contain multiple axes (plots). Axes-level methods operate on a single axes object inside the figure, controlling one plot area.
Examine the code below:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
fig.suptitle('Main Title')
ax.title('Sub Title')
plt.show()Why does the plot show the main title but not the sub title?
import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6]) fig.suptitle('Main Title') ax.title('Sub Title') plt.show()
Check the method names for setting titles on axes.
The method ax.title() does not exist, so no sub title is set. The correct method to set a title on axes is ax.set_title(). The fig.suptitle() correctly sets the main title for the figure.