统计图表之折线图

折线图主要用于展示数据的变化趋势。

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()

在这里插入图片描述

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值