Look at the code below that plots two lines with a legend. What will the legend show?
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6], label='Line A') plt.plot([1, 2, 3], [6, 5, 4], label='Line B') plt.legend() legend_texts = [text.get_text() for text in plt.gca().get_legend().get_texts()] print(legend_texts) plt.close() # Prevent showing plot in test environment
Check the order of plotting and the labels assigned.
The legend shows labels in the order the lines were plotted. The first line is labeled 'Line A', the second 'Line B'.
This code creates a heatmap with a colorbar. How many ticks will the colorbar display?
import matplotlib.pyplot as plt import numpy as np data = np.random.rand(5,5) fig, ax = plt.subplots() cax = ax.imshow(data, cmap='viridis') cb = fig.colorbar(cax, ticks=[0, 0.5, 1]) plt.close() tick_labels = [tick.get_text() for tick in cb.ax.get_yticklabels() if tick.get_text() != ''] print(len(tick_labels))
Look at the ticks argument passed to the colorbar.
The colorbar ticks are explicitly set to three values: 0, 0.5, and 1, so three ticks appear.
Given a scatter plot with points colored by a value, which code snippet correctly adds both a legend for categories and a colorbar for the color scale?
import matplotlib.pyplot as plt import numpy as np x = np.arange(5) y = np.random.rand(5) colors = np.linspace(0, 1, 5) categories = ['A', 'B', 'A', 'B', 'A'] fig, ax = plt.subplots() scatter = ax.scatter(x, y, c=colors, cmap='plasma')
Think about how to create legend entries for categories without plotting extra points.
Option C creates invisible scatter points for each category to add to the legend, then adds the colorbar for the color scale.
Consider this code snippet that tries to add a colorbar but raises an error. What is the error?
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() scatter = ax.scatter([1,2,3], [4,5,6]) fig.colorbar() plt.close()
Check the required arguments for fig.colorbar()
The colorbar function requires a mappable object (like the scatter) to know what to show. Omitting it causes a TypeError.
Which statement best explains why legends and colorbars help people understand plots better?
Think about how a reader knows what colors or symbols represent.
Legends and colorbars act as guides that explain what colors and symbols mean, helping readers understand the data clearly.