折线图主要用于展示数据的变化趋势。
1. 折线图的绘制
1.1 matplotlib的plot()函数
- x, y: 需要绘制的点的数据
- linestyle: 设置线条类型
- color: 设置线条颜色
- marker: 设置线条标记风格,‘+’为加号标记,'o’为圆圈,‘-’为实线,‘–’为虚线。
- linewidth: 设置线条宽度
- label: 设置线条标签
# 导入相应包
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x = np.linspace(0, 10, 1000) # 成0到10之间、长度为1000的等差数组
y = np.sin(x) # sin(x)
plt.plot(x, y, '--g', lw=2, label='sin(x)')
1.2 DataFrame或Series内置的plot()方法
- 接受1.1中参数
- kind: 指定绘图的类型。line(线图),bar(),barh(),hist(直方图),box(),kde(密度图),area(),pie(饼图)
data = pd.DataFrame(y, x)
data.plot(kind='line', linestyle='--', color='r', lw=2, label='sin(x)')
2. 标注点的绘制
当我们需要对图形的某些点加上标记时,我们可以使用matplotlib的annotate()函数
- s:标注文本内容
- xy:需要标注点的坐标,二维元组格式(x, y)
- xytext:标注文本的坐标,二维元组格式(x, y)
- xycoords:被标记的点的坐标系属性,默认为data(以x,y为参考)
- textcoords:标记文本的坐标系属性,默认与xycoords相同,通常设置为’offset points’或‘offset pixels’,即相对于标记点的偏移量。
- arrowprops:设置箭头的样式,dict格式:width, headwidth,headlength,shrink,facecolor
- bbox:设置标注文本周围的外框属性
fig = plt.figure(figsize=(12, 8))
# 在Figure对象中创建一个Axes对象,每个Axes对象即为一个绘图区域
ax = fig.add_subplot(111)
x = np.arange(10, 20)
y = np.around(np.log(x), 2)
ax.plot(x, y, marker='o')
ax.annotate(u'样式1', xy=(x[1], y[1]), xytext=(80, 10),
textcoords='offset points',
arrowprops=dict(arrowstyle='->',
connectionstyle='angle3,angleA=80,angleB=50'))
ax.annotate(u'样式2', xy=(x[3], y[3]), xytext=(80, 10),
textcoords='offset points',
arrowprops=dict(facecolor='black',shrink=0.05, width=5))
ax.annotate(u'样式3', xy=(x[5], y[5]), xytext=(80, 10),
textcoords='offset points',
arrowprops=dict(facecolor='green', headwidth=5, headlength=10),
bbox=dict(boxstyle='circle,pad=0.5', fc='yellow', ec='k', lw=1,
alpha=0.5))
ax.annotate(u'样式4', xy=(x[7], y[7]), xytext=(80, 10),
textcoords='offset points',
arrowprops=dict(facecolor='blue', headwidth=5, headlength=10),
bbox=dict(boxstyle='round,pad=0.5', fc='gray', ec='k', lw=1,
alpha=0.5))
plt.show()