B. Methods title(), xlabel(), ylabel() do not exist for the plot object.
C. Plotting requires plt.show() to display labels.
D. The DataFrame columns must be strings to set labels.
Solution
Step 1: Check method names on plot object
The plot object returned by pandas uses set_title(), set_xlabel(), and set_ylabel() methods, not title(), xlabel(), or ylabel().
Step 2: Identify the error
Calling plot.title() causes an AttributeError because the method does not exist.
Final Answer:
Methods title(), xlabel(), ylabel() do not exist for the plot object. -> Option B
Quick Check:
Use set_title, set_xlabel, set_ylabel methods [OK]
Hint: Use set_title, set_xlabel, set_ylabel methods [OK]
Common Mistakes:
Using title() instead of set_title()
Forgetting to call plt.show() (though not error here)
Assuming DataFrame columns affect label setting
5. You want to create a bar plot from a DataFrame df with columns 'Year' and 'Sales'. You want the plot to be 10 inches wide and 6 inches tall, with the title 'Annual Sales', x-axis label 'Year', and y-axis label 'Sales'. Which code snippet correctly achieves this?
hard
A. ax = df.plot.bar(x='Year', y='Sales')
plt.title('Annual Sales')
plt.xlabel('Year')
plt.ylabel('Sales')
plt.figure(figsize=(10,6))
B. df.plot.bar(x='Year', y='Sales', title='Annual Sales', x_label='Year', y_label='Sales', figsize=(10,6))
C. ax = df.plot.bar(x='Year', y='Sales', figsize=(10,6))
ax.set_title('Annual Sales')
ax.set_xlabel('Year')
ax.set_ylabel('Sales')
D. df.plot.bar(x='Year', y='Sales')
ax.set_title('Annual Sales')
ax.set_xlabel('Year')
ax.set_ylabel('Sales')
plt.figure(figsize=(10,6))
Solution
Step 1: Set figure size correctly
Figure size must be set in the plot.bar() call using figsize=(10,6). ax = df.plot.bar(x='Year', y='Sales', figsize=(10,6))
ax.set_title('Annual Sales')
ax.set_xlabel('Year')
ax.set_ylabel('Sales') does this correctly.
Step 2: Set title and axis labels on the Axes object
ax = df.plot.bar(x='Year', y='Sales', figsize=(10,6))
ax.set_title('Annual Sales')
ax.set_xlabel('Year')
ax.set_ylabel('Sales') uses ax.set_title(), ax.set_xlabel(), and ax.set_ylabel() which is the correct way to set labels after plotting.
Step 3: Check other options
df.plot.bar(x='Year', y='Sales', title='Annual Sales', x_label='Year', y_label='Sales', figsize=(10,6)) tries to pass title and labels directly to plot.bar(), which is not supported. ax = df.plot.bar(x='Year', y='Sales')
plt.title('Annual Sales')
plt.xlabel('Year')
plt.ylabel('Sales')
plt.figure(figsize=(10,6)) sets figure size after plotting, which has no effect. df.plot.bar(x='Year', y='Sales')
ax.set_title('Annual Sales')
ax.set_xlabel('Year')
ax.set_ylabel('Sales')
plt.figure(figsize=(10,6)) uses ax without defining it and sets figure size after plotting, which is incorrect.