import matplotlib.pyplot as plt
import numpy as np
文字 (text)
# 创建带数字标签的直方图
numbers = list(range(1,10))
# np.array()将列表转换为0存储单一数据类型的多维数组
x = np.array(numbers)
y = np.array([a**2 for a in numbers])
plt.bar(x,y,width=0.5,align='center',color='c')
plt.axis([0,11,0,110])
for a,b in zip(x,y):
# 注入文字 a, b+0.1 代表 x y轴上的值
plt.text(a,b+0.1,'%.0f'%b,ha = 'center',va = 'bottom',fontsize=7)
plt.show()
注释(annotate)
和 文字方法略有不同
# 创建带数字标签的直方图
numbers = list(range(1,10))
# np.array()将列表转换为0存储单一数据类型的多维数组
x = np.array(numbers)
y = np.array([a**2 for a in numbers])
plt.bar(x,y,width=0.5,align='center',color='c')
plt.axis([0,11,0,110])
for xy in zip(x, y):
height = xy[1]
plt.annotate("(%s)" % height, xy=xy, xytext=(-10, 5), textcoords='offset points')
plt.show()
公式 (text)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([1,7])
ax.set_ylim([1,5])
ax.text(2,4,r"$\frac{5 - \frac{1}{x}}{4}$", size=25)
plt.show()
画图形(patches)
from matplotlib import patches
#绘制一个椭圆需要制定椭圆的中心,椭圆的长和高
xcenter, ycenter = 1,1
width, height = 0.8,0.5
angle = -30 #椭圆的旋转角度
# 第一步:创建绘图对象(椭圆)
fig = plt.figure()
ax = fig.add_subplot(211, aspect='auto')
ax.set_xbound(-1,3)
ax.set_ybound(-1,3)
#第二步 创建相对应的图形形状
e1 = patches.Ellipse((xcenter, ycenter), width, height,
angle=angle, linewidth=2, fill=False, zorder=2)
#第三步 将图形添加到图中
ax.add_patch(e1)
#第一步 创建绘图对象(圆)
ax = fig.add_subplot(212, aspect='equal')
ax.set_xbound(-1,3)
ax.set_ybound(-1,3)
#第二步 创建相对应的图形形状
e2 = patches.Circle((xcenter, ycenter), radius=2, alpha=0.5)
#第三步 将图形添加到图中
ax.add_patch(e2)
plt.show()
填充 (fill, fill_between)
# 创建带数字标签的直方图
numbers = list(range(1,10))
# np.array()将列表转换为0存储单一数据类型的多维数组
x = np.array(numbers)
y = np.array([a**2 for a in numbers])
plt.bar(x,y,width=0.5,align='center',color='c')
plt.axis([0,11,0,110])
for xy in zip(x, y):
height = xy[1]
plt.annotate("(%s)" % height, xy=xy, xytext=(-10, 5), textcoords='offset points')
plt.show()
样式 (style)
样式共有26种
print(plt.style.available)
['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'Solarize_Light2', 'tableau-colorblind10', '_classic_test']
x = np.linspace(0, 10, 1000)
y = np.sin(x) + 1
z = np.cos(x) + 1
fig = plt.figure(figsize = (8, 4))
plt.plot(x,y,label='$\sin x+1$', color = 'red', linewidth = 2)
plt.plot(x,z,'b--',label='$\cos x^2+1$')
# plt.fill(x,y, 'b', alpha=0.3)
# plt.fill(x,z, 'r', alpha=0.3)
ax = plt.gca()
ax.fill_between(x, y, z, where=z>=y,facecolor='yellow')
ax.fill_between(x, y, z, where=z<y, facecolor='red')
plt.style.use('dark_background')
# plt.style.use('fast')
plt.show()