matplotlib 绘图详解

2023-01-12  本文已影响0人  敬子v

matplotlib

Matplotlib是一个帮助我们绘制数据的python库。通过它,你可以画出线图、散点图、等高线图; 条形图、直方图、3D 图形甚至是图形动画等等。

当横轴为时间时,使用线图
当两个变量存在相关性时,使用散点图
当想要观察数值数据的分布时,使用直方图
我们可以在图表中定义以下属性:颜色、标签、线宽、标题、不透明度、网格、图形大小、坐标轴刻度、线型等

条形图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x=np.arange(1,6)
y=np.random.randint(1,100,5) #随机生成5个1到100之间的数

条形图:维度分类较多或维度名称比较长的时候使用横向树状图(条形图)

plt.bar(x,y,color='g')
plt.show()

堆积图:更直观对比整体的数据,可以更清晰的看出各种类别的占比情况

y.plot(kind='barh',stacked=True,figsize=(16,9)) #传递参数stacked=True来生成堆积树状图
plt.show()

百分比堆积树状图:展示的占比的情况

y.div(data.sum(1),axis=0).plot(kind='barh',figsize=(16,9),stacked=True)
plt.show()

直方图

x=np.random.randn(500)
plt.hist(x,bins=20,color='g',rwidth=0.5)
plt.show()

散点图

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(10)
y_c=np.random.normal(size=10)
plt.scatter(x,y_c,color='y')

饼图

from matplotlib import pyplot as plt
a=np.random.randint(1,10,5)
plt.pie(a,autopct="%1.2f%%",shadow=True,explode=(0,0,0.3,0,0),startangle=90)
plt.show()
  #让饼图保持正圆形
  plt.axis('equal')
  plt.show()

参数解释:
y 为dataframe列名,或者列名列表,当绘制多列数据,指定subplots=True,绘制在不同的子图中
autopct:在图中显示百分比
shadow:布尔值,为饼图增加阴影效果
explode:为饼图增加破裂效果,值越大,破裂越大
startangle:饼图旋转角度,从X轴逆时针旋转

折线图

*在图中截取2007-2010年金融危机部分*

```python
#截取2007-2011年
#set_xlim, setylim:设置图表的边界

ax.set_xlim(['2007-1-1','2011-1-1'])

#截取SPX>600
ax.set_ylim([600,1800])

#添加标题
ax.set_title('2007-2010年金融危机标普500指数变化趋势')

#添加坐标轴标签
ax.set_xlabel('Date')
ax.set_ylabel('SPX')
```

*在图中添加文字*

```python
# ax.annotate('Peak of bull market',xy=(datetime(2007,10,11),y['2007-10-11']),
           xytext=(datetime(2007,10,11),y['2007-10-11'] + 160),
           arrowprops=dict(facecolor='c'))
"""
s:字符串,注释文本
xy:注释的点(x,y)
xytext:放置文本的位置(x,y)
arrowprops:在xy和xytext之间绘制箭头的属性(字典)
"""

crisis_date = [
    (datetime(2007,10,11),'Peak of bull market'),
    (datetime(2008,3,12),'Bear Stearns Fails'),
    (datetime(2008,9,15),'Lehman Bankruptcy')
]

for date,label in crisis_date:
    ax.annotate(label,xy=(date,y[date]),xytext=(date,y[date]+160),
               arrowprops=dict(facecolor='c'))
```



*关于annotate更多请参考:*

*https://matplotlib.org/api/_as_gen/matplotlib.pyplot.annotate.html*

*https://matplotlib.org/users/annotations_intro.html*

*在这里我们另外补充了面向对象画图的另外几个功能*

箱线图

x=np.random.randint(1,11,10)
plt.boxplot(x)
print(x)
plt.show()

matplotlib参数调整

matplotlib图像构造

matplotlib绘制子图

从上图我们可以看出,我们子图和子图之间默认会有一定的间距,我们可以使用subplots_adjust对间距进行调整

subplts_adjust(wspace, hspace)

wspace:宽度百分比:

hspace:高度百分比

#调整子图的间距
plt.subplots_adjust(wspace=0,hspace=0) #消除了子图与子图之间的间距
#创建一个2*1的画布
fig,axs = plt.subplots(2,1,figsize=(16,6),dpi=100,sharex=True)

#多个子图进行绘图的时候,我们需要选择我们绘图区(axes)
#选择第一个axes
axs[0].plot(x,y,color='r',linestyle='--',marker='o',label='A')
#选择第二个axes
axs[1].plot(x,y_B,color='b',marker='D',label='B')

axs[0].legend()
axs[1].legend()

axs[0].grid(linestyle='--',alpha=1)
axs[1].grid(linestyle='--',alpha=1)

axs[0].set_title('A股票10分中的涨幅')
axs[1].set_title('B股票10分中的涨幅')

axs[0].set_xlabel('时间')
axs[1].set_xlabel('时间')

axs[0].set_ylabel('涨幅')
axs[1].set_ylabel('涨幅')  

#在创建画布的时候,设置了sharex=True,所有的子图共享x轴刻度
axs[0].set_xticks(x)
axs[0].set_xticklabels(x_ticks_label)

plt.show()
上一篇 下一篇

猜你喜欢

热点阅读