
上QQ阅读APP看书,第一时间看更新
How it works...
Here is the explanation of how the code works:
- fig, ax = plt.subplots(1,2) defines the figure with two axis objects on the same row. Since it is only one row with two plots, ax is a one-dimensional vector, so we will access them with ax[0] and ax[1].
- line = lines.Line2D([0*cm, 1.5*cm], [0*cm, 2.5*cm], lw=2, color='black', axes=ax[0]) plots a black line segment on axis ax[0], with line width 2, and input data, in centimeters.
- Similarly, t = text.Text(3*cm, 2.5*cm, 'text label', ha='left', va='bottom', axes=ax[0]) defines a text label object to ax[0] at the specified position (3, 2.5) in centimeters with the left alignment horizontally and a bottom alignment vertically.
It should be noted that Matplotlib does not support sharing objects across different axes; we need to explicitly specify for each object in which axes it is to be included. We specified axes=ax[0] for the line plot, since the same line is plotted again on ax[1], and we had to tell Matplotlib on which axis it is plotting the line at any given time. This also means that if the same line or text is to be drawn on two different axis, then it will have to be repeated twice.
- ax[0].add_line(line) and ax[0].add_artist(t) add the line and text objects on ax[0]. Remember, artist is an object that actually draws the object on the canvas/chart. In fact, add_line can also be replaced with add_artist, as we have done for ax[1] later.
- ax[0].xaxis.set_units(cm) and ax[0].yaxis.set_units(cm) set the units of measurement for the x axis and the y axis for actual display. For ax[0], this is set to centimeters, and for ax[1], this is set to inches. For both axes, the input data is in centimeters.
- ax[0].grid(True) shows the grid, along with the major ticks on both the x and the y axis. This helps in visualizing the exact coordinate values anywhere on the graph.
- plt.suptitle() sets the title for the figure, plt.tight_layout(pad=3) adjusts the space between the plots, and pad=3 ensures that the figure title sufficiently precedes the figure.
- Exactly the same steps are repeated for ax[1], the only the difference being that ax[1].xaxis.set_units(inch) and ax[1].yaxis.set_units(inch) are specified in inches instead of cm.
Here is how the figure looks:

Since the scales are the same on both of the plots, the size of the line is smaller in inches than in centimeters, as expected.