matplotlib绘图以及参数设置

1.matplotlib官方文档

链接

2.matplotlib入门篇

import matplotlib.pyplot as plt
plt.figure(figsize=(10,6))
x =[1,2,7]
y =[5,7,4]
plt.plot(x,y)
plt.rcParams['font.sans-serif']=['SimHei']
plt.show()

  • 绘制折线图

适用场景:折线图适合二维的大数据集,还适合多个二维数据集的比较。一般用来表示趋势的变化,横轴一般为日期字段

x=[1,2,3,4,5,6,7,8]                                                                             
y =[5,2,4,2,1,4,5,2]
plt.plot(x,y,label = '折线图')                            
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.title('绘制折线图')
plt.legend()
plt.show()

  •  绘制柱状图或者条形图

适用场景:显示各个项目之间的比较情况,和柱状图类似的作用

x1 =[1,3,5,7,9]
x2 =[2,4,6,8,10]
y1=[5,2,7,8,2]
y2 =[8,6,2,5,6]
plt.bar(x1,y1,label='bar1')
plt.bar(x2,y2,label='bar2')
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.title('柱形图')
plt.legend()
plt.show()

  • 绘制直方图

 直方图非常像条形图,倾向于通过将区段组合在一起来显示分布。频率分布直方图,能清楚显示各组频数分布情况又易于显示各组之间频数的差别。

让我们能够更好了解数据的分布情况,因此其中组距、组数起关键作用。分组过少,数据就非常集中;分组过多,数据就非常分散,这就掩盖了分布的特征。当数据在100以内时,一般分5~12组为宜。

population_ages =[22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]
# 分组
bins= [0,10,20,30,40,50,60,70,80,90,100,110,120,130]
plt.hist(population_ages,bins,label='直方图')
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.title('直方图')
plt.legend()
plt.show()

3. matplotlib进阶篇

from matplotlib import pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

fig=plt.figure(1)
ax1=plt.subplot(121)
data=np.array([15,20,18,25])
width=0.5
x_bar=np.arange(4)

ax1.bar(x_bar,data,width=width,label='简易的bar')
plt.xlabel('季度')
plt.ylabel('销量')
plt.legend()
plt.show()

添加text

ax2=plt.subplot(122)

#创建ax2图的对象
rects = ax2.bar(x_bar,data,width=width,label='进阶的bar',color='red')
for rect in rects:
    #获取x轴的数据
    x_val = rect.get_x()
    #获取y轴的值
    y_val = rect.get_height()
    ax2.text(x_val+0.08,y_val+0.2,str(y_val)+'W')

plt.xlabel('季度')
plt.ylabel('销量')
plt.legend()
plt.show()

 

添加x轴label

 fig2 = plt.figure(2)
ax3=plt.subplot(121)
rects = ax3.bar(x_bar,data,width=width,label='高进阶的bar',color='green')
for rect in rects:
    #获取x轴的数据
    x_val = rect.get_x()
    #获取y轴的值
    y_val = rect.get_height()
    ax3.text(x_val+0.08,y_val+0.2,str(y_val)+'W')
plt.xticks(x_bar,('第一季度','第二季度','第三季度','第四季度'))
plt.xlabel('季度')
plt.ylabel('销量')
plt.grid(True)
plt.legend()
plt.show()

猜你喜欢

转载自blog.csdn.net/qq_20412595/article/details/81213012
今日推荐