
上QQ阅读APP看书,第一时间看更新
How to do it...
The following code block draws two plots, one with centimeters and the other with inches, to demonstrate the difference between two units of measurement:
- Define a figure with two plots in a row:
fig, ax = plt.subplots(1,2)
- Define line and the text artists to be added to the first axis:
line = lines.Line2D([0*cm, 1.5*cm], [0*cm, 2.5*cm], lw=2,
color='black', axes=ax[0])
t = text.Text(3*cm, 2.5*cm, 'text label', ha='left', va='bottom',
axes=ax[0])
- Add the artists to axis 0, and set the limits, units of measurement, and the grid:
ax[0].add_line(line)
ax[0].add_artist(t)
ax[0].set_xlim(-1*cm, 10*cm)
ax[0].set_ylim(-1*cm, 10*cm)
ax[0].xaxis.set_units(cm)
ax[0].yaxis.set_units(cm)
ax[0].grid(True)
- Define the line and text artists to be added to the second axis:
line = lines.Line2D([0*cm, 1.5*cm], [0*cm, 2.5*cm], lw=2,
color='black', axes=ax[1])
t = text.Text(3*cm, 2.5*cm, 'text label', ha='left', va='bottom',
axes=ax[1])
- Add the artists to axes 1 and set limits, units of measurement, and grid:
ax[1].add_artist(line)
ax[1].add_artist(t)
ax[1].set_xlim(-1*cm, 10*cm)
ax[1].set_ylim(-1*cm, 10*cm)
ax[1].xaxis.set_units(inch)
ax[1].yaxis.set_units(inch)
ax[1].grid(True)
- Set the title for the figure and adjust the space between the plots:
plt.suptitle("Demonstration of Units Of Measurement")
plt.tight_layout(pad=3)
- Display the figure on the screen:
plt.show()