Python Matplotlib 散点图:绘制每月牙膏销售量
使用 Python Matplotlib 绘制每月牙膏销售量散点图
本示例将展示如何使用 Python Matplotlib 库绘制每月牙膏销售量的散点图,并自定义图例位置、标识点样式、图题、轴标签和网格形式。
代码:
import matplotlib.pyplot as plt
# 数据
months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
sales = [100, 120, 90, 80, 110, 130, 150, 140, 120, 110, 100, 90]
# 绘制散点图
plt.scatter(months, sales, marker='x', color='blue')
# 添加图例
plt.legend(['Toothpaste'], loc='upper left')
# 添加图题
plt.title('图二:牙膏售卖量散点图')
# 添加轴标签
plt.xlabel('Month Number')
plt.ylabel('Number of Units Sold')
# 添加背景网格
plt.grid(True, linestyle='-')
# 显示图形
plt.show()
代码解释:
- 导入 Matplotlib 库:
import matplotlib.pyplot as plt - 定义数据:
months和sales变量分别存储月份和对应月份的销售量。 - 绘制散点图:
plt.scatter(months, sales, marker='x', color='blue')使用scatter函数绘制散点图,并设置标识点为蓝色叉叉(marker='x', color='blue')。 - 添加图例:
plt.legend(['Toothpaste'], loc='upper left')使用legend函数添加图例,并将其放置在左上角(loc='upper left')。 - 添加图题:
plt.title('图二:牙膏售卖量散点图')使用title函数添加图题。 - 添加轴标签:
plt.xlabel('Month Number')和plt.ylabel('Number of Units Sold')使用xlabel和ylabel函数添加 X 轴和 Y 轴标签。 - 添加背景网格:
plt.grid(True, linestyle='-')使用grid函数添加网格,并设置网格形式为横线(linestyle='-')。 - 显示图形:
plt.show()使用show函数显示绘制的散点图。
注意: 该代码需要在 Jupyter Notebook 或者其他支持 Matplotlib 的 Python 环境中运行。
原文地址: https://www.cveoy.top/t/topic/bP3b 著作权归作者所有。请勿转载和采集!