介绍
这篇文章主要讲解了python matplotlib模块绘制基本图形的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
matplotlib模块是python中一个强大的绘图模块
安装<代码> pip install matplotlib 代码>
首先我们来画一个简单的图来感受它的神奇
进口numpy np 进口matplotlib。pyplot作为plt 进口matplotlib zhfont1=matplotlib.font_manager.FontProperties(?癝imHei.ttf") # - - - - - - -设置字体,这个可以事先下载https://www.fontpalace.com/font-details/SimHei/
x=np.arange(1) 1, 11日# - - - - - - -从数字1到11,步长为1 y=2 * x + 5
plt.title(“我是标题“,fontproperties=zhfont1) # - - - - - - - - - -设置标题 plt.xlabel (“x坐标标题“,fontproperties=zhfont1) # - - - - - - - - - - - -设置x坐标名称 plt.ylabel (“y坐标标题“,fontproperties=zhfont1) # - - - - - - - - - - - -设置y坐标名称 plt.plot (x, y) # - - - - - - - - - - - -开始绘制plt.plot (x, y,“: r")表示使用虚线红颜色绘制
plt.show() # - - - - - - - - - - - -显示图形
,下面是简单的图形
2一个图片上绘制多个子图:次要情节
进口numpy np 进口matplotlib。pyplot作为plt 进口matplotlib zhfont1=matplotlib.font_manager.FontProperties(?癝imHei.ttf") #计算正弦和余弦曲线上的点的x和y坐标 x=np。(0,3 * np不等。π,0.1) y_sin=np.sin (x) y_cos=np.cos (x) #激活第一个次要情节 plt。次要情节(2、2、1) #绘制第一个图像 plt。情节(x, y_sin) plt.title(& # 39;正弦-坐标图1 & # 39;,fontproperties=zhfont1) plt.xlabel (& # 39; x1 # 39;) plt.ylabel (& # 39; y1 # 39;)
#将第二个次要情节激活,并绘制第二个图像 plt。次要情节(2 2 2) plt。情节(x, y_cos) plt.title (& # 39; cos -坐标图2 & # 39;,fontproperties=zhfont1) plt.xlabel (& # 39; x2 # 39;) plt.ylabel (& # 39; y2 # 39;) #展示图像 plt.show ()
图形如下
说明:从上图我们可以看到出现了两个子图
plt.subplot用来激活子图,plt.subplot (& # 39; x坐标分成几个& # 39;,& # 39;y坐标分成几个& # 39;,& # 39;本身是第几个& # 39;):x * y就是把图片分成几个平等位置,最后的参数表示放在哪个位置,位置表示如下,从左到右,从上到下
1 2 3 4
如果要让上面的图对角表示呢,
修改为
plt。次要情节(2、2、1)
plt。次要情节(2,2,4)
, 3绘制直方图
进口numpy np 进口matplotlib。pyplot作为plt 进口matplotlib # zhfont1=matplotlib.font_manager.FontProperties(?癝imHei.ttf") plt.rcParams [& # 39; font.family& # 39;]=& # 39; SimHei& # 39; x=[0、1、2、3、4) y=[15] 20、10、30、25日 str1=(“北京“,“上海“,“武汉“,“深圳“,“重庆“) plt.bar (x,身高=y,宽度=0.5,标签=俺鞘泄ぷ省?tick_label=str1) # tick_label要显示的名称 #为a, b在zip (x, y): # plt。文本(a, b + 0.05, & # 39; % .0f& # 39;% b,公顷=& # 39;中心# 39;,va=& # 39;底部# 39;字形大?10) #分别按照坐标给出数据标签 plt.text(0, 20 + 0.05 20公顷=& # 39;中心# 39;,va=& # 39;底部# 39;,字形大?10)#简单说(x位置,y位置+ 0.05,要显示的数据,水平中心对齐,垂直底部对齐,字体大小) plt.text(10 + 0.05 10公顷=& # 39;中心# 39;,va=& # 39;底部# 39;,字形大?10) plt.text(2, 30 + 0.05, 30公顷=& # 39;中心# 39;,va=& # 39;底部# 39;,字形大?10) plt.text(25 + 0.05, 25公顷=& # 39;中心# 39;,va=& # 39;底部# 39;,字形大?10) plt.text(15 + 0.05, 15日,4公顷=& # 39;中心# 39;,va=& # 39;底部# 39;,字形大?10) plt.legend() #用来显示标签标签的内容 plt.show ()
下面显示图形
, 4绘制条形图(直方图的一种)
进口numpy np 进口matplotlib。pyplot作为plt 进口matplotlib # zhfont1=matplotlib.font_manager.FontProperties(?癝imHei.ttf") plt.rcParams [& # 39; font.family& # 39;]=& # 39; SimHei& # 39; x_label=[& # 39; 2015 & # 39; & # 39; 2016 & # 39;, & # 39; 2017 & # 39;, & # 39; 2018 & # 39;, & # 39; 2019 & # 39;] #横坐标刻度显示 日元=[15]20、10、30、25日#纵坐标值 y2=[15、15、30、40、20) y3=[20] 23岁,35岁,40岁,25日 x=范围(len (y1)) str1=(“北京“,“上海“,“武汉“)python matplotlib模块绘制基本图形的方法