使用python的matplotlib进行绘图
Python的matplotlib第三方库绘图时主要分为以下四个层次,分别是Canvas(画板)、Figure(画布)、axes(子图)、图表信息(构图元素)四个层次。
在绘图时主要分为以下六个步骤:
- 导入matplotlib库的pyplot模块。
- 准备绘图数据。
- 设置matplotlib参数以正确显示中文和负号。
- 创建画布。
- 绘制指定类型的图形。
- 添加标签等图例。
- 保存并展示图形。
1.导入matplotlib库的pyplot模块。
import matplotlib.pyplot as plt
2.准备绘图数据。
products = ['产品 A', '产品 B', '产品 C'] # 横坐标
sales = [120, 85, 150] # 纵坐标
3.设置matplotlib参数以正确显示中文和负号
plt.rcParams["font.family"] = ["SimHei"] # 设置字体以正确显示中文
plt.rcParams["axes.unicode_minus"] = False # 确保负号正常显示
4.创建画布
plt.figure(figsize=(8, 5))
5.绘制指定类型的图形
bar是柱形图,plot线图,scatter散点图,hist直方图,pie饼图,boxplot箱线图。雷达图需要特殊处理得到。本例以柱图为例。
bars = plt.bar(products, sales, color=['green', 'orange', 'purple'], width=0.6)
6.添加标签等图例
遍历每一个柱设置标签的坐标和文字。然后设置标题和轴标签。
for bar in bars:height = bar.get_height()plt.text(bar.get_x() + bar.get_width()/2, height + 5, str(height), ha='center')
plt.title('3 种产品季度销量柱状图', fontsize=12)
plt.xlabel('产品类型', fontsize=10)
plt.ylabel('销量(件)', fontsize=10)
7.保存并展示图形
plt.savefig('柱状图.png', dpi=300)
plt.show()
8. 完整代码
import matplotlib.pyplot as pltproducts = ['产品 A', '产品 B', '产品 C'] # 横坐标
sales = [120, 85, 150] # 纵坐标plt.rcParams["font.family"] = ["SimHei"] # 设置字体以正确显示中文
plt.rcParams["axes.unicode_minus"] = False # 确保负号正常显示plt.figure(figsize=(8, 5))bars = plt.bar(products, sales, color=['green', 'orange', 'purple'], width=0.6)for bar in bars:height = bar.get_height()plt.text(bar.get_x() + bar.get_width()/2, height + 5, str(height), ha='center')
plt.title('3 种产品季度销量柱状图', fontsize=12)
plt.xlabel('产品类型', fontsize=10)
plt.ylabel('销量(件)', fontsize=10)plt.savefig('柱状图.png', dpi=300)
plt.show()
