What will be the output of this Python code using matplotlib?
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y1 = [10, 20, 30, 40, 50] y2 = [100, 200, 300, 400, 500] fig, ax1 = plt.subplots() ax1.plot(x, y1, 'g-') ax2 = ax1.twinx() ax2.plot(x, y2, 'b--') plt.show()
Remember that twinx() creates a second y-axis sharing the same x-axis.
The code creates one figure with two y-axes. The first axis plots y1 with a green solid line on the left y-axis. The second axis, created by twinx(), plots y2 with a blue dashed line on the right y-axis.
Given this code snippet, how many major ticks will appear on the left and right y-axes respectively?
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y1 = [10, 20, 30, 40, 50] y2 = [100, 200, 300, 400, 500] fig, ax1 = plt.subplots() ax1.plot(x, y1, 'r-') ax2 = ax1.twinx() ax2.plot(x, y2, 'b-') left_ticks = len(ax1.get_yticks()) right_ticks = len(ax2.get_yticks()) print(left_ticks, right_ticks)
Default matplotlib y-axis ticks usually include the min and max plus intermediate ticks.
By default, matplotlib creates 5 major ticks on each y-axis for these ranges. Both axes have 5 ticks.
What error will this code produce?
import matplotlib.pyplot as plt x = [1, 2, 3] y1 = [10, 20, 30] y2 = [100, 200, 300] fig, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(x, y1, 'r-') ax2.plot(x, y2, 'b-') ax1.set_ylabel('Y1') ax2.set_ylabel('Y2') ax1.set_xlabel('X') ax2.set_xlabel('X') plt.show()
Check if setting xlabel on both axes causes an error or just overwrites.
Both axes share the same x-axis, so setting xlabel on both does not cause an error. The last call overwrites the label, but no error occurs.
Which option best describes the visual difference between these two plots?
Plot 1: Single y-axis plotting y1 and y2 on the same scale.
Plot 2: Dual y-axis plotting y1 on left and y2 on right with different scales.
Think about how different scales affect line visibility on one axis.
Plot 1 forces both lines on one scale, causing one line to appear flat or distorted. Plot 2 uses two y-axes to show both lines clearly.
Why would a data scientist choose to use a dual y-axis plot?
Think about when one y-axis scale is not enough to show both data sets clearly.
Dual y-axis plots allow comparing two variables with different units or scales on the same x-axis without distortion.