或许这个小例子可以解开对matplotlib的ax和plt迷惑

1.官方样例代码

https://matplotlib.org/gallery/lines_bars_and_markers/simple_plot.html

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()

fig.savefig("test.png")
plt.show()

2.通过plt.gca(),plt.gcf获得figure和ax对象

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
plt.subplots()
plt.plot(t,s)
ax = plt.gca()
ax.set(xlabel='time',ylabel='voltage(mV)',title='FINE')
fig = plt.gcf()
fig.savefig('test.png')
plt.show()

3.通过plt获得figure和ax对象

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
plt.subplots()
plt.plot(t,s)
plt.xlabel = 'time'
plt.ylabel = 'valtage(mV)')
plt.title='Fine'
plt.savefig('test.png')
plt.show()

猜你喜欢

转载自blog.csdn.net/weixin_38246633/article/details/85342556
今日推荐