- Matplotlib 3.0 Cookbook
- Srinivasa Rao Poladi
- 173字
- 2025-04-04 16:06:37
How to do it...
The following code displays two plots for the same input data, but the first one uses default settings so it displays a full range of data on both the x and the y axes, whereas the second plot limits both the x and y axes range:
- Prepare the data for the graph:
x = np.linspace(-50,50,500)
y = x**2 + np.cos(x)*100
- Define a function to format numeric data before printing on the plot:
def Num_Format(x, pos):
"""The two arguments are the number and tick position"""
if x >= 1e6:
string = '${:1.1f}M'.format(x*1e-6)
else:
string = '${:1.0f}K'.format(x*1e-3)
return string
- Apply the function defined earlier to the formatter, and define the figure with size and layout:
formatter = FuncFormatter(Num_Format)
fig, axs = plt.subplots(1,2, figsize=(8,5))
- Plot a line graph on the first axis with autoscale:
axs[0].plot(x, y**2)
axs[0].yaxis.set_major_formatter(formatter)
axs[0].set_title('Full Data/Autoscale')
- Plot the same graph again with limits applied on both the x and y axis:
axs[1].plot(x, y**2)
axs[1].set(xlim=(-5,5), ylim=(0,10000), title='X and Y limited')
axs[1].yaxis.set_major_formatter(formatter)
- Display the figure on the screen:
plt.show()