目录
- 1. 绘制折线图
- 1.1 绘制简单的折线图
- 1.2 修改图表的初始值
- 1.3 多组数据的应用
- 1.4 设置线条颜色及样式
- 1.5 刻度设置
- 1.6 图例legend()
- 2. 绘制散点图
- 2.1 基本散点图的绘制 绘制一个点
- 2.2 设置绘制区间
- 2.3 绘制波形
- 2.4 创建不等宽的散点图
- 2.5 色彩映射
- 2.6 利用随机数绘制散点图
- 2.7 利用随机数实现位置的移动
- 3. 绘制多个图表
- 3.1 一个程序绘制多个图表
- 3.2 含有子表的图表
- 4. 绘制直方图
- 5. 使用CSV文件绘制图表
- 参考:
- 总结
matplotlib绘图库模块安装
pip install matplotlib
导入pyplot子模块
import matplotlib.pyplot as plt
官网:http://matplotlib.org
官方文档:https://matplotlib.org/stable/index.html
1. 绘制折线图
1.1 绘制简单的折线图
import matplotlib | |
import matplotlib.pyplot as plt | |
# 设置字体为微软雅黑,解决中文显示问题 | |
matplotlib.rc("font", family='Microsoft YaHei') | |
#.准备数据 | |
squares = [, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] | |
#.画线plot() | |
# linewidth设置线条宽度 | |
plt.plot(squares, linewidth=) # 列表内的数据被视为y轴的值,x轴的值会根据列表值的索引位置自动产生 | |
#.设置x、y轴的最小刻度和最大刻度 | |
plt.axis([, 10, 0, 100]) # 将x轴设为0~10,将y轴设为0~100 | |
#.设置标题及字体大小 | |
""" | |
title():图表标题,title(标题名称,fontsize=字体大小) | |
xlabel():x轴标题 | |
ylabel():y轴标题 | |
""" | |
plt.title(label='~10的平方', fontsize=18) | |
plt.xlabel(xlabel='值', fontsize=) | |
plt.ylabel(ylabel='平方值', fontsize=) | |
#.设置坐标轴刻度 | |
""" | |
使用tick_params()方法设置: | |
- 应用范围(axis):x-->应用到x轴,y-->应用到y轴,both-->应用到x轴和y轴 | |
- 坐标轴的刻度大小(labelsize) | |
- 线条颜色(color) | |
如:tick_params(axis='x', labelsize=, color='green') | |
""" | |
plt.tick_params(axis='both', labelsize=, color='red', labelcolor='green') | |
# 显示绘制的图形 | |
plt.show() |
效果:
1.2 修改图表的初始值
import matplotlib | |
import matplotlib.pyplot as plt | |
# 设置字体为微软雅黑,解决中文显示问题 | |
matplotlib.rc("font", family='Microsoft YaHei') | |
#.准备数据 | |
squares = [, 4, 9, 16, 25, 36, 49, 64, 81, 100] | |
# 索引列表 | |
seq = [, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
#.画线plot() | |
# linewidth设置线条宽度 | |
plt.plot(seq, squares, linewidth=.5) | |
# 设置标题及字体大小 | |
plt.title(label='~10的平方', fontsize=18) | |
plt.xlabel(xlabel='值', fontsize=) | |
plt.ylabel(ylabel='平方值', fontsize=) | |
#.设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red', labelcolor='green') | |
# 显示绘制的图形 | |
plt.show() |
效果:
1.3 多组数据的应用
# author:mlnt | |
# createdate:/8/17 | |
import matplotlib | |
import matplotlib.pyplot as plt | |
# 设置字体为微软雅黑,解决中文显示问题 | |
matplotlib.rc("font", family='Microsoft YaHei') | |
#.准备数据 | |
data = [1, 4, 9, 16, 25, 36, 49, 64, 81] | |
data = [1, 3, 5, 8, 13, 21, 34, 55, 89] | |
# 索引列表 | |
seq = [, 2, 3, 4, 5, 6, 7, 8, 9] | |
#.画线plot() | |
# linewidth设置线条宽度 | |
plt.plot(seq, data, seq, data2, linewidth=2.5) | |
# 设置标题及字体大小 | |
plt.title(label='Test Chart', fontsize=) | |
plt.xlabel(xlabel='x-value', fontsize=) | |
plt.ylabel(ylabel='y-value', fontsize=) | |
#.设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red', labelcolor='green') | |
# 显示绘制的图形 | |
plt.show() |
效果:
1.4 设置线条颜色及样式
设置颜色,可在plot()中添加参数:
- ‘b’: blue
- ‘c’: cyan
- ‘g’: green
- ‘k’: black
- ‘m’: magenta
- ‘r’: red
- ‘w’: white
- ‘y’: yellow
设置线条样式:
- '-‘或’solid’: 预设实线
- '–‘或’dashed’: 虚线
- '-.‘或’dashdot’: 虚点线
- ':‘或’dotted’:点线
- ‘.’:点标记
- ‘,’:像素标记
- ‘o’: 圆标记
- ‘v’: 反三角标记
- ‘^’: 三角标记
- ‘s’:方形标记
- ‘p’:五角标记
- ‘*’: 星号标记
- ‘+’:加号标记
- ‘-’:减号标记
import matplotlib.pyplot as plt | |
#.准备数据 | |
data = [1, 2, 3, 4, 5, 6, 7, 8, 9] # data1线条 | |
data = [1, 4, 9, 16, 25, 36, 49, 64, 81] # data2线条 | |
data = [1, 3, 5, 8, 13, 21, 34, 55, 89] # data3线条 | |
data = [1, 6, 12, 20, 30, 41, 56, 72, 90] # data4线条 | |
# 索引列表 | |
seq = [, 2, 3, 4, 5, 6, 7, 8, 9] | |
plt.plot(seq, data, 'g--', seq, data2, 'r-.', seq, data3, 'b:', seq, data4, 'mp') | |
# 设置标题及字体大小 | |
plt.title(label='Test Chart', fontsize=) | |
plt.xlabel(xlabel='x-value', fontsize=) | |
plt.ylabel(ylabel='y-value', fontsize=) | |
# 设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red') | |
plt.show() |
效果:
1.5 刻度设置
import matplotlib | |
import matplotlib.pyplot as plt | |
# 设置字体为微软雅黑,解决中文显示问题 | |
matplotlib.rc("font", family='Microsoft YaHei') | |
#.准备数据 | |
gold_medal = [, 5, 16, 16, 28, 32, 51, 38, 26, 38] | |
silver_medal = [, 11, 22, 22, 16, 17, 21, 27, 18, 32] | |
bronze_medal = [, 12, 16, 12, 15, 14, 28, 23, 26, 18] | |
# 索引列表 | |
year = [, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021] | |
""" | |
设置刻度: | |
- xticks():设置x轴刻度 | |
- yticks():设置y轴刻度 | |
""" | |
# 设置x轴刻度 | |
plt.xticks(year) | |
# 设置线条样式 | |
plt.plot(year, gold_medal, '-*', year, silver_medal, '-o', year, bronze_medal, '-^') | |
# 设置标题及字体大小 | |
plt.title('中国历届奥运会奖牌情况', fontsize=) | |
plt.xlabel('年份', fontsize=) | |
plt.ylabel('数量/枚', fontsize=) | |
# 设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red') | |
# 显示图表 | |
plt.show() |
效果:
1.6 图例legend()
参数loc可以设置图例的位置:
- ‘best’: 0,
- ‘upper right’: 1 ,–>右上角
- ‘upper left’: 2,–>左上角
- ‘lower left’: 3,–>左下角
- ‘lower right’: 4,–>右下角
- ‘right’: 5,
- ‘center left’: 6,–>左侧中央
- ‘center right’: 7,–>右侧中间
- ‘lower center’: 8,–>底部正中
- ‘upper center’: 9,–>顶部正中
- ‘center’: 10
将图例放在图表内
import matplotlib | |
import matplotlib.pyplot as plt | |
# 设置字体为微软雅黑,解决中文显示问题 | |
matplotlib.rc("font", family='Microsoft YaHei') | |
#.准备数据 | |
gold_medal = [, 5, 16, 16, 28, 32, 51, 38, 26, 38] | |
silver_medal = [, 11, 22, 22, 16, 17, 21, 27, 18, 32] | |
bronze_medal = [, 12, 16, 12, 15, 14, 28, 23, 26, 18] | |
# 索引列表 | |
year = [, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021] | |
""" | |
设置刻度: | |
- xticks():设置x轴刻度 | |
- yticks():设置y轴刻度 | |
""" | |
# 设置x轴刻度 | |
plt.xticks(year) | |
# 设置线条样式 | |
line_gold, = plt.plot(year, gold_medal, '-*', label='gold_medal') | |
line_silver, = plt.plot(year, silver_medal, '-o', label='silver_medal') | |
line_bronze, = plt.plot(year, bronze_medal, '-^', label='bronze_medal') | |
# 设置图例 | |
""" | |
参数loc可以设置图例的位置 | |
'best':, | |
'upper right':,-->右上角 | |
'upper left':,-->左上角 | |
'lower left':,-->左下角 | |
'lower right':,-->右下角 | |
'right':, | |
'center left':,-->左侧中央 | |
'center right':,-->右侧中间 | |
'lower center':,-->底部正中 | |
'upper center':,-->顶部正中 | |
'center': | |
""" | |
plt.legend(handles=[line_gold, line_silver, line_bronze], loc='best') | |
# 放在图表内的右上角 | |
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc=) | |
# 放在图表内的左上角 | |
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc='upper left') | |
# 放在图表内的左下角 | |
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc=) | |
# 放在图表内的右下角 | |
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc=) | |
# 放在图表内的左侧中央 | |
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc='center left') | |
# 放在图表内的右侧中央 | |
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc='center right') | |
# 放在图表内的底部正中 | |
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc='lower center') | |
# 放在图表内的顶部正中 | |
# plt.legend(handles=[line_gold, line_silver, line_bronze], loc='upper center') | |
# 设置标题及字体大小 | |
plt.title('中国历届奥运会奖牌情况', fontsize=) | |
plt.xlabel('年份', fontsize=) | |
plt.ylabel('数量/枚', fontsize=) | |
# 设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red') | |
# 显示图表 | |
plt.show() |
效果:
将图例放在图表外,使用savefig()方法保存图片文件
# author:mlnt | |
# createdate:/8/17 | |
import matplotlib | |
import matplotlib.pyplot as plt | |
# 设置字体为微软雅黑,解决中文显示问题 | |
matplotlib.rc("font", family='Microsoft YaHei') | |
#.准备数据 | |
gold_medal = [, 5, 16, 16, 28, 32, 51, 38, 26, 38] | |
silver_medal = [, 11, 22, 22, 16, 17, 21, 27, 18, 32] | |
bronze_medal = [, 12, 16, 12, 15, 14, 28, 23, 26, 18] | |
# 索引列表 | |
year = [, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021] | |
""" | |
设置刻度: | |
- xticks():设置x轴刻度 | |
- yticks():设置y轴刻度 | |
""" | |
# 设置x轴刻度 | |
plt.xticks(year) | |
# 设置线条样式 | |
line_gold, = plt.plot(year, gold_medal, '-*', label='gold_medal') | |
line_silver, = plt.plot(year, silver_medal, '-o', label='silver_medal') | |
line_bronze, = plt.plot(year, bronze_medal, '-^', label='bronze_medal') | |
# 设置图例 | |
# bbox_to_anchor()设置锚点,即图例位置 | |
# 在图表内,左下角位置为(,0),右上角位置为(1,1) | |
plt.legend(handles=[line_gold, line_silver, line_bronze], loc='best', bbox_to_anchor=(, 1)) | |
# 设置在图表与Figure之间留白 | |
# h_pad/w_pad分别设置高度/宽度的留白 | |
plt.tight_layout(pad=) | |
# 设置标题及字体大小 | |
plt.title('中国历届奥运会奖牌情况', fontsize=) | |
plt.xlabel('年份', fontsize=) | |
plt.ylabel('数量/枚', fontsize=) | |
# 设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red') | |
# 保存图片文件,使用savefig()方法保存图片文件,需放在show()的前面,表示先存储再显示图表 | |
plt.savefig('medal_chart.jpg', bbox_inches='tight') # bbox_inches='tight'将图表的多余空间删除 | |
# 显示图表 | |
plt.show() |
效果:
2. 绘制散点图
2.1 基本散点图的绘制 绘制一个点
""" | |
scatter(x, y, s, c) | |
s: 绘图点的大小 | |
c:颜色 | |
""" | |
import matplotlib.pyplot as plt | |
# 在坐标轴(,5)绘制一个点 | |
plt.scatter(, 5) | |
plt.show() |
效果:
绘制系列点
# author:mlnt | |
# createdate:/8/17 | |
""" | |
scatter(x, y, s, c) | |
s: 绘图点的大小 | |
c:颜色 | |
""" | |
import matplotlib.pyplot as plt | |
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签 | |
plt.rcParams['axes.unicode_minus'] = False | |
medal = [, 28, 54, 50, 59, 63, 100, 88, 70, 88] | |
# 索引列表 | |
year = [, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021] | |
# 设置x轴刻度 | |
plt.xticks(year) | |
plt.scatter(x=year, y=medal, s=, c='green') | |
# 设置标题及字体大小 | |
plt.title('中国历届奥运会奖牌情况', fontsize=) | |
plt.xlabel('年份', fontsize=) | |
plt.ylabel('数量/枚', fontsize=) | |
# 设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red') | |
plt.show() |
效果:
2.2 设置绘制区间
**axis()**设置绘图区间:
axis([xmin, xmax, ymin, ymax])
- xmin/xmax:x轴的最小/最大区间
- ymin/ymxa:y轴的最小/最大区间
# author:mlnt | |
# createdate:/8/17 | |
""" | |
axis()设置绘图区间: | |
axis([xmin, xmax, ymin, ymax]) | |
xmin/xmax:x轴的最小/最大区间 | |
ymin/ymxa:y轴的最小/最大区间 | |
""" | |
import matplotlib.pyplot as plt | |
plt.rcParams['font.sans-serif'] = ['SimHei'] | |
plt.rcParams['axes.unicode_minus'] = False | |
x = [i for i in range(, 101)] | |
y = [i** for i in x] | |
# 设置绘图区间 | |
plt.axis([, 100, 0, 10000]) | |
plt.scatter(x=x, y=y, s=, c='green') | |
# 设置标题及字体大小 | |
plt.title('-100的平方', fontsize=20) | |
plt.xlabel('数值', fontsize=) | |
plt.ylabel('平方值', fontsize=) | |
# 设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red') | |
plt.show() |
效果:
2.3 绘制波形
import matplotlib.pyplot as plt | |
import numpy as np | |
x = np.linspace(, 10, 500) | |
# 绘制sin()和cos()的波形变化 | |
y = np.sin(x) | |
y = np.cos(x) | |
plt.scatter(x, y, color=(0.5, 0.8, 0.6)) | |
plt.scatter(x, y) | |
plt.show() |
效果:
2.4 创建不等宽的散点图
import matplotlib.pyplot as plt | |
import numpy as np | |
x = np.linspace(, 5, 500) | |
y = - 0.5*np.abs(x-2) | |
lwidths = (+x)**2 | |
plt.scatter(x=x, y=y, s=lwidths, color=(.6, 0.8, 0.9)) | |
plt.show() |
效果:
2.5 色彩映射
import matplotlib.pyplot as plt | |
import numpy as np | |
x = np.arange() | |
plt.scatter(x=x, y=x, c=x, cmap='rainbow') | |
plt.show() |
效果:
2.6 利用随机数绘制散点图
import matplotlib.pyplot as plt | |
import numpy as np | |
while True: | |
x = np.random.random() | |
y = np.random.random() | |
t = x | |
plt.scatter(x, y, s=, c=t, cmap='brg') | |
plt.show() | |
is_exit = input('是否继续?(y/n)') | |
if is_exit.upper() == 'N': | |
break |
2.7 利用随机数实现位置的移动
# author:mlnt | |
# createdate:/8/17 | |
import random | |
import matplotlib.pyplot as plt | |
def loc(index): | |
"""处理坐标的移动""" | |
x_mov = random.choice([-, 3]) | |
xloc = x[index -] + x_mov | |
y_mov = random.choice([-, -1, 1, 5]) | |
yloc = y[index -] + y_mov | |
x.append(xloc) | |
y.append(yloc) | |
num = | |
x = [] | |
y = [] | |
while True: | |
for i in range(, num): | |
loc(i) | |
t = x | |
plt.scatter(x, y, s=, c=t, cmap='brg') | |
# plt.axes().get_xaxis().set_visible(False) # 隐藏y坐标 | |
# plt.axes().get_yaxis().set_visible(False) # 隐藏y坐标 | |
# 隐藏坐标轴。 | |
plt.axis('off') | |
plt.savefig('image.png', bbox_inches='tight', pad_inches=) | |
plt.show() | |
is_exit = input('是否继续?(y/n)') | |
if is_exit.upper() == 'N': | |
break | |
else: | |
x[] = x[num - 1] | |
y[] = y[num - 1] | |
del x[:] | |
del y[:] |
3. 绘制多个图表
3.1 一个程序绘制多个图表
# author:mlnt | |
# createdate:/8/17 | |
import matplotlib.pyplot as plt | |
#.准备数据 | |
data = [1, 4, 9, 16, 25, 36, 49, 64, 81] | |
data = [1, 3, 5, 8, 13, 21, 34, 55, 89] | |
# 索引列表 | |
seq = [, 2, 3, 4, 5, 6, 7, 8, 9] | |
# 创建图表 | |
plt.figure() | |
# 画线plot() | |
plt.plot(seq, data, '-*') | |
# 创建图表 | |
plt.figure() | |
plt.plot(seq, data, '-o') | |
# 设置标题及字体大小 | |
plt.title(label='Test Chart', fontsize=18) | |
plt.xlabel(xlabel='x-value', fontsize=) | |
plt.ylabel(ylabel='y-value', fontsize=) | |
#.设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red', labelcolor='green') | |
# 显示绘制的图形 | |
plt.show() |
效果:
3.2 含有子表的图表
subplot(x1, x2, x3)
- x1: 上下(垂直)方向绘制图表数
- x2:左右(水平)方向绘制图表数
- x3:表示这是第几张
一个Figure内绘制上下子图
# author:mlnt | |
# createdate:/8/17 | |
""" | |
subplot(x, x2, x3) | |
x: 上下(垂直)方向绘制图表数 | |
x:左右(水平)方向绘制图表数 | |
x:表示这是第几张 | |
""" | |
import matplotlib.pyplot as plt | |
#.准备数据 | |
data = [1, 4, 9, 16, 25, 36, 49, 64, 81] | |
data = [1, 3, 5, 8, 13, 21, 34, 55, 89] | |
# 索引列表 | |
seq = [, 2, 3, 4, 5, 6, 7, 8, 9] | |
# 在一个Figure内绘制上下子图 | |
plt.subplot(, 1, 1) | |
# 画线plot() | |
plt.plot(seq, data, '-*') | |
plt.subplot(, 1, 2) | |
plt.plot(seq, data, '-o') | |
# 设置标题及字体大小 | |
plt.xlabel(xlabel='x-value', fontsize=) | |
plt.ylabel(ylabel='y-value', fontsize=) | |
# 设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red', labelcolor='green') | |
# 显示绘制的图形 | |
plt.show() |
效果:
一个Figure内绘制左右子图
# author:mlnt | |
# createdate:/8/17 | |
""" | |
subplot(x, x2, x3) | |
x: 上下(垂直)方向绘制图表数 | |
x:左右(水平)方向绘制图表数 | |
x:表示这是第几张 | |
""" | |
import matplotlib.pyplot as plt | |
#.准备数据 | |
data = [1, 4, 9, 16, 25, 36, 49, 64, 81] | |
data = [1, 3, 5, 8, 13, 21, 34, 55, 89] | |
# 索引列表 | |
seq = [, 2, 3, 4, 5, 6, 7, 8, 9] | |
# 在一个Figure内绘制上下子图 | |
plt.subplot(, 1, 1) | |
# 画线plot() | |
plt.plot(seq, data, '-*') | |
plt.subplot(, 1, 2) | |
plt.plot(seq, data, '-o') | |
# 设置标题及字体大小 | |
plt.xlabel(xlabel='x-value', fontsize=) | |
plt.ylabel(ylabel='y-value', fontsize=) | |
# 设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red', labelcolor='green') | |
# 显示绘制的图形 | |
plt.show() |
效果:
4. 绘制直方图
# author:mlnt | |
# createdate:/8/17 | |
""" | |
bar(x, height, width) | |
x: 序列,x轴位置 | |
height:序列数值大小 | |
width:直方图的宽度 | |
""" | |
import matplotlib.pyplot as plt | |
import numpy as np | |
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签 | |
plt.rcParams['axes.unicode_minus'] = False | |
medal = [, 28, 54, 50, 59, 63, 100, 88, 70, 88] | |
x = np.arange(len(medal)) | |
# 索引列表 | |
year = [, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021] | |
plt.bar(x, medal, width=.5) | |
# 设置标题及字体大小 | |
plt.title('中国历届奥运会奖牌情况', fontsize=) | |
plt.xlabel('年份', fontsize=) | |
plt.ylabel('数量/枚', fontsize=) | |
plt.xticks(x, year) | |
# 设置坐标轴刻度 | |
plt.tick_params(axis='both', labelsize=, color='red') | |
plt.show() |
效果:
# author:mlnt | |
# createdate:/8/17 | |
import matplotlib.pyplot as plt | |
import numpy as np | |
plt.rcParams['font.sans-serif'] = ['SimHei'] | |
plt.rcParams['axes.unicode_minus'] = False | |
#.准备数据 | |
labels = [, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021] | |
gold_medal = [, 5, 16, 16, 28, 32, 51, 38, 26, 38] | |
silver_medal = [, 11, 22, 22, 16, 17, 21, 27, 18, 32] | |
bronze_medal = [, 12, 16, 12, 15, 14, 28, 23, 26, 18] | |
x = np.arange(len(labels)) # x轴位置 | |
width =.3 # 直方图的宽度 | |
fig, ax = plt.subplots() | |
rects = ax.bar(x - width, gold_medal, width, label='gold_medal') | |
rects = ax.bar(x, silver_medal, width, label='silver_medal') | |
rects = ax.bar(x + width, bronze_medal, width, label='bronze_medal') | |
# 设置标题及字体大小 | |
ax.set_xlabel('年份', fontsize=) | |
ax.set_ylabel('数量/枚', fontsize=) | |
ax.set_title('中国历届奥运会奖牌情况', fontsize=) | |
ax.set_xticks(x, labels) | |
# 设置图例 | |
ax.legend() | |
ax.bar_label(rects, padding=3) | |
ax.bar_label(rects, padding=3) | |
ax.bar_label(rects, padding=3) | |
fig.tight_layout() | |
plt.show() |
效果:
5. 使用CSV文件绘制图表
# author:mlnt | |
# createdate:/8/17 | |
import csv | |
import matplotlib | |
import matplotlib.pyplot as plt | |
matplotlib.rc("font", family='Microsoft YaHei') | |
filename = 'score.csv' | |
with open(file=filename) as csvFile: # 打开csv文件 | |
csvReader = csv.reader(csvFile) # 创建reader对象 | |
headerRow = next(csvReader) # 读取文件下一行 | |
print(headerRow) # ['学号', '姓名', '语文', '数学', '英语', '物理', '化学', '生物'] | |
# 设置空列表 | |
names, Chinese, Math, English, Physics, Chemistry, Biology = [], [], [], [], [], [], [] | |
for row in csvReader: | |
# 将数据添加到列表 | |
names.append(row[]) | |
Chinese.append(int(row[])) | |
Math.append(int(row[])) | |
English.append(int(row[])) | |
Physics.append(int(row[])) | |
Chemistry.append(int(row[])) | |
Biology.append(int(row[])) | |
print(f'语文:{Chinese}') | |
print(f'数学:{Math}') | |
print(f'英语:{English}') | |
print(f'物理:{Physics}') | |
print(f'化学:{Chemistry}') | |
print(f'生物:{Biology}') | |
# 绘制语文成绩 | |
# 设置绘图区大小 | |
fig = plt.figure(dpi=, figsize=(12, 8)) | |
# 设置线条样式 | |
line_Chinese, = plt.plot(names, Chinese, '-*', label='Chinese') | |
line_Math, = plt.plot(names, Math, '-o', label='Math') | |
line_English, = plt.plot(names, English, '-p', label='English') | |
line_Physics, = plt.plot(names, Physics, '-s', label='Physics') | |
line_Chemistry, = plt.plot(names, Chemistry, '-v', label='Chemistry') | |
line_Biology, = plt.plot(names, Biology, '-^', label='Biology') | |
# 设置图例 | |
plt.legend(handles=[line_Chinese, line_Math, line_English, line_Physics, line_Chemistry, line_Biology], loc='best') | |
# 旋转 | |
fig.autofmt_xdate(rotation=) | |
plt.title('成绩分析', fontsize=) | |
plt.xlabel('学员', fontsize=) | |
plt.ylabel('分数', fontsize=) | |
plt.tick_params(axis='both', labelsize=, color='red') | |
plt.show() |
score.csv:
效果:
# author:mlnt | |
# createdate:/8/17 | |
import csv | |
from datetime import datetime | |
import matplotlib | |
import matplotlib.pyplot as plt | |
matplotlib.rc("font", family='Microsoft YaHei') | |
filename = 'temperature.csv' | |
with open(file=filename) as csvFile: # 打开csv文件 | |
csvReader = csv.reader(csvFile) # 创建reader对象 | |
headerRow = next(csvReader) # 读取文件下一行 | |
# print(headerRow) | |
# 设置空列表 | |
dates, lowTemps, highTemps, averageTemps = [], [], [], [] | |
for row in csvReader: | |
try: | |
# 将日期字符串转成对象 | |
currentDate = datetime.strptime(row[], '%Y/%m/%d') | |
# 设置最低温度 | |
# 需要转换成数字类型,y轴才能进行排序 | |
lowTemp = float(row[]) | |
# 设置最高温度 | |
highTemp = float(row[]) | |
# 设置平均温度 | |
averageTemp = float(row[]) | |
except Exception as e: | |
print('有缺值', e) | |
else: | |
# 将数据添加到列表 | |
dates.append(currentDate) | |
lowTemps.append(lowTemp) | |
highTemps.append(highTemp) | |
averageTemps.append(averageTemp) | |
print(f'最低温度:{lowTemps}') | |
print(f'最高温度:{highTemps}') | |
print(f'平均温度:{averageTemps}') | |
# # 设置绘图区大小 | |
fig = plt.figure(dpi=, figsize=(12, 8)) | |
# 设置线条样式 | |
line_highTemps, = plt.plot(dates, highTemps, '-*', label='highTemps') | |
line_lowTemps, = plt.plot(dates, lowTemps, '-o', label='lowTemps') | |
line_averageTemps, = plt.plot(dates, averageTemps, '-p', label='averageTemps') | |
# 设置图例 | |
plt.legend(handles=[line_lowTemps, line_averageTemps, line_highTemps], loc='best') | |
# 旋转 | |
fig.autofmt_xdate(rotation=) | |
plt.title('Weather Report', fontsize=) | |
plt.xlabel('Date', fontsize=) | |
plt.ylabel('Temperature (C)', fontsize=) | |
plt.tick_params(axis='both', labelsize=, color='red') | |
plt.show() |
temperature.csv:
效果:
参考:
- 官网:http://matplotlib.org
- 官方文档:https://matplotlib.org/stable/index.html
- 色彩映射:http://matplotlib.org/examples/color/colormaps_reference.html
- https://www.pudn.com/news/62623526dfdd9a1c0c529522.html
- https://www.yzlfxy.com/jiaocheng/python/430158.html
- https://www.zhihu.com/question/506015285