一、折线图绘制参数详解
plt.plot(x, y, linestyle, linewidth, color, marker,markersize, markeredgecolor,markerfactcolor,markeredgewidth, label, alpha)
- x:指定折线图的x轴数据
- y:指定折线图的y轴数据
- linestyle:指定折线的类型,可以是实线、虚线、点虚线、点点线等,默认为实线
- linewidth:指定折线的宽度
- marker:可以为折线图添加点,该参数是设置点的形状
- markersize:设置点的大小
- markeredgecolor:设置点的边框色
- markerfactcolor:设置点的填充色
- markeredgewidth:设置点的边框宽度
- label:为折线图添加标签,类似于图例的作用
1 import pandas as pd
2 import matplotlib.pyplot as plt
3 # 导入模块,用于日期刻度的修改
4 import matplotlib as mpl
5 # 数据读取
6 wechat = pd.read_excel('wechat.xlsx')
7 # 绘制单条折线图
8 plt.plot(wechat.Date, # x轴数据
9 wechat.Counts, # y轴数据
10 linestyle = '-', # 折线类型
11 linewidth = 2, # 折线宽度
12 color = 'steelblue', # 折线颜色
13 marker = 'o', # 折线图中添加圆点
14 markersize = 6, # 点的大小
15 markeredgecolor='black', # 点的边框色
16 markerfacecolor='brown') # 点的填充色
17
18 # 获取图的坐标信息
19 ax = plt.gca()
20 # 设置日期的显示格式
21 date_format = mpl.dates.DateFormatter("%y-%m-%d")
22 ax.xaxis.set_major_formatter(date_format)
23 # 设置x轴显示多少个日期刻度
24 # xlocator = mpl.ticker.LinearLocator(10)
25 # 设置x轴每个刻度的间隔天数
26 xlocator = mpl.ticker.MultipleLocator(7)
27 ax.xaxis.set_major_locator(xlocator)
28 # 为了避免x轴刻度标签的紧凑,将刻度标签旋转45度
29 plt.xticks(rotation=45)
30
31 # 添加y轴标签
32 plt.ylabel('人数')
33 # 添加图形标题
34 plt.title('每天微信文章阅读人数趋势')
35 # 显示图形
36 plt.show()
②透视表pivot_table参数说明链接:javascript:void(0)
1 # 读取天气数据
2 weather = pd.read_excel('weather.xlsx')
3 # 统计每月的平均最高气温
4 data = weather.pivot_table(index = 'month', columns='year', values='high')
5 print(data)
6 # 绘制折线图
7 data.plot(kind = 'line',
8 style = ['-','--',':'] # 设置折线图的线条类型
9 )
10 # 修改x轴和y轴标签
11 plt.xlabel('月份')
12 plt.ylabel('气温')
13 # 添加图形标题
14 plt.title('每月平均最高气温波动趋势')
15 # 显示图形
16 plt.show()