hello,大家好,我是wangzirui32,今天来教大家如何利用数据可视化库matplotlib绘制多种图表。
开始学习吧!
1. 安装matplotlib
输入pip安装指令:
pip install matplotlib
没有报错即安装成功。
2. 折线图
先来看一个最最最简单的例子:绘制折线统计图。代码如下:
import matplotlib.pyplot as plt
input_numbers = [1, 2, 3, 4, 5] # X轴数值
numbers = [10, 20, 30, 40, 50] # Y轴数值
# 传入数字列表 设置线条宽度为5
plt.plot(input_numbers, numbers, linewidth=5)
# 设置标题 设置字体大小
plt.title("maplotlib-test", fontsize=24)
# 设置X,Y轴说明文字 并设置字体大小
plt.xlabel("X", fontsize=14)
plt.ylabel("Y", fontsize=14)
# 保存图表 bbox_inches='tight'将图表的多余空白部分去除
plt.savefig("折线统计图.png", bbox_inches='tight')
# 展示图表
plt.show()
运行代码,保存的图表如下:
可以看到,标题,XY轴的说明都正确的显示了出来。
3. 散点图
import matplotlib.pyplot as plt
x_values = [1, 2, 3, 4, 5]
y_values = [5, 10, 15, 20, 25]
# 传入点的x,y参数 设置点的大小为100
plt.scatter(x_values, y_values, s=100)
# 绘制图表说明参数
plt.title("maplotlib-test2", fontsize=24)
plt.xlabel("X"