介绍
- Matplotlib 是基于 Python 的开源项目,旨在为 Python 提供一个数据绘图包。
绘图原理
- 在 Matplotlib 中,整个图像为一个 Figure 对象,在 Figure 对象中可以包含一个或多个 Axes 对象:
def matplotlib_theory():
fig = Figure()
canvas = FigureCanvas(fig)
ax1 = fig.add_axes([0.1, 0.6, 0.3, 0.3])
ax2 = fig.add_axes([0.6, 0.6, 0.3, 0.3])
ax3 = fig.add_axes([0.1, 0.1, 0.3, 0.3])
ax4 = fig.add_axes([0.6, 0.1, 0.3, 0.3])
line1 = ax1.plot([0, 1], [0, 1])
ax1.set_title("a straight line ")
ax1.set_xlabel("x label")
ax1.set_ylabel("y label")
line2 = ax2.plot([2, 5], [2, 5])
ax2.set_title("a straight line ")
ax2.set_xlabel("x")
ax2.set_ylabel("y")
canvas.print_figure('figure.jpg')
绘图分解
plt.style.use('bmh')
x = np.linspace(0,5,10)
y = x ** 2
plt.plot(x, y, 'r--')
plt.title('title')
plt.xlabel('x')
plt.ylabel('y')
plt.text(2, 10, 'y=x*x')
plt.annotate('this is annotate', xy=(3.5, 12), xytext=(2,16), arrowprops={'headwidth':10, 'facecolor':'r'})
plt.legend(['y=x^2'])
plt.grid(linestyle='--', linewidth=1)
plt.xlim(left=0, right=5)
plt.ylim(bottom=0, top=25)
x = pd.date_range('2020/01/01',periods=30)
y = np.arange(0,30,1)**2
plt.plot(x,y,'r')
plt.gcf().autofmt_xdate()
plt.show()
x = np.linspace(1, 5, 10)
y = x ** 2
plt.plot(x, y, 'r')
plt.text(3, 10, 'y=x^2')
plt.twinx()
plt.plot(x, np.log(x), 'g')
plt.text(1.5, 0.4, 'y=logx')
x = np.linspace(1, 5, 10)
y = x ** 2
plt.subplot(1, 2, 1)
plt.plot(x, y, 'r--')
plt.subplot(1, 2, 2)
plt.plot(y, x, 'g*-')
x = np.linspace(1, 5, 10)
y = x ** 2
fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3])
axes1.plot(x, y, 'r')
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('title')
axes2.plot(y, x, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title')
plt.show()
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong']
mpl.rcParams['axes.unicode_minus'] = False
plt.plot(x, y, 'r')
plt.title('显示中文标题')
plt.show()
from matplotlib import animation
from random import randint, random
class Data:
data_count = 32
frames_count = 2
def __init__(self, value):
self.value = value
self.color = (0.5, random(), random())
@classmethod
def create(cls):
return [[Data(randint(1, cls.data_count)) for _ in range(cls.data_count)]
for frame_i in range(cls.frames_count)]
def draw_chart():
fig = plt.figure(1, figsize=(16, 9))
axs = fig.add_subplot(111)
axs.set_xticks([])
axs.set_yticks([])
frames = Data.create()
def animate(fi):
axs.cla()
axs.set_xticks([])
axs.set_yticks([])
return axs.bar(list(range(Data.data_count)),
[d.value for d in frames[fi]],
1,
color=[d.color for d in frames[fi]]
)
anim = animation.FuncAnimation(fig, animate, frames=len(frames))
plt.show()