一. 折线图
import numpy as np
import matplotlib.pyplot as plt
import random
y_1 = [random.randint(0,10) for _ in range(20)]
y_2 = [random.randint(0,10) for _ in range(20)]
x = range(11,31)
#设置图形大小,dpi使得图片更清晰(设置分辨率的)
plt.figure(figsize=(20,8),dpi=80)
#label是为了区分,可以在legend中显示
plt.plot(x,y_1,label="自己",color="#F08080",linestyle=":")
plt.plot(x,y_2,label="同桌",color="#DB7093",linestyle="--")
#设置x轴刻度
_xtick_labels = ["{}岁".format(i) for i in x]
plt.xticks(x,_xtick_labels,fontproperties="STSong")#显示中文
plt.yticks(range(0,9))
#绘制网格
plt.grid(alpha=0.8,linestyle=':')
#添加图例
plt.legend(prop="STSong",loc="upper left")
#标题
plt.title("交朋友数量比较图",fontproperties="STSong")
#x,y轴坐标
plt.xlabel("年龄",fontproperties="STSong")
plt.ylabel("数量",fontproperties="STSong")
效果:
二. 散点图
from matplotlib import pyplot as plt
y_3 = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23]
y_10 = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6]
x_3 = range(1,32)
x_10 = range(51,82)
#设置图形大小
plt.figure(figsize=(20,8),dpi=80)
#使用scatter方法绘制散点图,和之前绘制折线图的唯一区别
plt.scatter(x_3,y_3,label="3月份")
plt.grid(True)
plt.scatter(x_10,y_10,label="10月份")
#调整x轴的刻度
_x = list(x_3)+list(x_10)
_xtick_labels = ["3月{}日".format(i) for i in x_3]
_xtick_labels += ["10月{}日".format(i-50) for i in x_10]
plt.xticks(_x[::3],_xtick_labels[::3],fontproperties="STSong",rotation=45)
#添加图例
plt.legend(loc="upper left",prop="STSong")
#添加描述信息
plt.xlabel("时间",fontproperties="STSong")
plt.ylabel("温度",fontproperties="STSong")
plt.title("标题",fontproperties="STSong")
效果:
三. 条形图
from matplotlib import pyplot as plt
a = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:殊死一战","蜘蛛侠:英雄归来","悟空传","银河护卫队2","情圣","新木乃伊",]
b=[56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23]
#设置图形大小
plt.figure(figsize=(20,15),dpi=80)
#绘制条形图,width是每条的宽
plt.bar(range(len(a)),b,width=0.8)
#设置字符串到x轴
plt.xticks(range(len(a)),a,fontproperties="STSong",rotation=90)
效果:
四. 横向条形图
from matplotlib import pyplot as plt
a = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:殊死一战","蜘蛛侠:英雄归来","悟空传","银河护卫队2","情圣","新木乃伊",]
b=[56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23]
#设置图形大小
plt.figure(figsize=(20,8),dpi=80)
#绘制条形图,height是每条的高
plt.barh(range(len(a)),b,height=0.3,color="orange")
#设置字符串到x轴
plt.yticks(range(len(a)),a,fontproperties="STSong")
plt.xticks(range(60))
plt.title("电影排行",fontproperties="STSong")
plt.xlabel("数量",fontproperties="STSong")
plt.ylabel("电影名",fontproperties="STSong")
plt.grid(alpha=0.3)
#保存图片
# plt.savefig("./movie.png")
效果:
五. 直方图
from matplotlib import pyplot as plt
a=[131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128,
142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126, 134, 95, 138,
117, 111,78, 132, 124, 113, 150, 110, 117, 86, 95, 144, 105, 126, 130,126, 130, 126, 116, 123,
106, 112, 138, 123, 86, 101, 99, 136,123, 117, 119, 105, 137, 123, 128, 125, 104, 109, 134, 125,
127,105, 120, 107, 129, 116, 108, 132, 103, 136, 118, 102, 120, 114,105, 115, 132, 145, 119, 121,
112, 139, 125, 138, 109, 132, 134,156, 106, 117, 127, 144, 139, 139, 119, 140, 83, 110, 102,123,
107, 143, 115, 136, 118, 139, 123, 112, 118, 125, 109, 119, 133,112, 114, 122, 109, 106, 123, 116,
131, 127, 115, 118, 112, 135,115, 146, 137, 116, 103, 144, 83, 123, 111, 110, 111, 100, 154,136,
100, 118, 119, 133, 134, 106, 129, 126, 110, 111, 109, 141,120, 117, 106, 149, 122, 122, 110, 118,
127, 121, 114, 125, 126,114, 140, 103, 130, 141, 117, 106, 114, 121, 114, 133, 137, 92,121, 112, 146,
97, 137, 105, 98, 117, 112, 81, 97, 139, 113,134, 106, 144, 110, 137, 137, 111, 104, 117, 100, 111,
101, 110,105, 129, 137, 112, 120, 113, 133, 112, 83, 94, 146, 133, 101,131, 116, 111, 84, 137, 115,
122, 106, 144, 109, 123, 116, 111,111, 133, 150]
#计算组数
d = 3 #组距
num_bins = (max(a)-min(a))//d #分了多少组
#设置图形的大小
plt.figure(figsize=(20,8),dpi=80)
plt.hist(a,num_bins,density=True)
#设置x轴的刻度
plt.xticks(range(min(a),max(a)+d,d))
plt.grid()
效果:
六. 分区域划分
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1, 20)
y = x.reshape(-1, 1)
h = x * y
# 10-30 30-50 50-70 分割区间
cs = plt.contourf(h, levels=[10, 30, 50,70],
colors=['black', 'white', 'yellow'], extend='both') #extend是确定着色范围的
cs.cmap.set_over('red')
cs.cmap.set_under('blue')
cs.changed()
效果:
七. 类似等高线
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 50) # 生成连续数据
y = np.linspace(-3, 3, 50) # 生成连续数据
X, Y = np.meshgrid(x, y)
# 生成能够在坐标系中形成点阵的数组,这个可以去参考一下别的文章
# https://lixiaoqian.blog.csdn.net/article/details/81532855 这里讲的比较详细
Z = X**2 + Y**2 # 这里将高度设置为x^2+y^2,就能画一个圆形的等高线
C = plt.contour(x,y, Z ,colors=['k', 'k', 'k','r','r'], linestyles=['--','--', '-', '--','--'],
levels=[2,5, 8,10])
plt.clabel(C, inline=True, fontsize=10) #图中标签左右空白
八. 画子图
子图上常用的方法
在 ax 对象上定义了和 plt 类似的图形绘制函数,常用的有: plot, hist, scatter, bar, barh, pie。
在fig对象为整体画布,可以设置画布祥光的属性
- ax.grid(True) 可以加灰色网格
- set_xscale, set_title, set_xlabel 分别可以设置坐标轴的规度(指对数坐标等)、标题、轴名
- fontproperties=“STSong” 该属性用来显示中文
样例
import numpy as np
import matplotlib.pyplot as plt
fig,axs=plt.subplots(2,5,figsize=(10,4),sharex=True,sharey=True)
fig.suptitle("样例1",size=20,fontproperties="STSong")
for i in range(2):
for j in range(5):
axs[i][j].scatter(np.random.randn(10), np.random.randn(10))
axs[i][j].set_title('第%d行,第%d列'%(i+1,j+1),fontproperties="STSong")
axs[i][j].set_xlim(-5,5)
axs[i][j].set_ylim(-5,5)
axs[i][j].grid(True)
if i==1: axs[i][j].set_xlabel('横坐标',fontproperties="STSong")
if j==0: axs[i][j].set_ylabel('纵坐标',fontproperties="STSong")
fig.tight_layout()
效果:
九. 动图
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# 1.准备数据
date=[20200317,20200318,20200319,20200320,20200321,20200322,20200323,20200324,
20200325,20200326,20200327,20200328,20200329,20200330,20200331,20200401,
20200402,20200403,20200404,20200405]
values=[926.0,822.0,737.0,592.0,506.0,459.0,458.0,492.0,405.0,541.0,385.0,478.0,337.0,288.0,190.0,195.0,175.0,199.0,226.0,128.0]
#准备横轴数据
x=list(range(len(date)))
# 2. 创建画布
fig=plt.figure(figsize=(10,6))
# 3.初始化折线图和坐标轴
line,=plt.plot([],[],color='r')
#设置y轴范围
plt.ylim(0,max(values))
#设置x轴范围
x_range=10
plt.xlim(0,x_range)
#设置x轴刻度
plt.xticks(x[0:x_range],date[0:x_range])
#每一帧显示几条数据
line_range=6
# 4.实现动画更新方法
def update(i):
#更新折线图
start=0 if i-line_range<0 else i-line_range
#结束索引
end=i+1
line.set_data(x[start:end],values[start:end])
#更新横轴
if i>line_range:
#计算横轴的结束索引
x_end=i+(x_range-line_range) if i+(x_range-line_range) <len(x) else len(x)
#设置横轴的数据范围
plt.xlim(start,x_end)
#更新X轴刻度
plt.xticks(x[start:x_end],date[start:x_end])
return line
# 5.创建动画
animation=FuncAnimation(fig,update,frames=x)
# 6.展示
plt.show()
效果:
声明
本文只介绍了常用的图表实现,若想实现复杂的图片功能,需参考官方文档.另外,可以参考matplotlib官网,提供了更多的图表实现.