使用 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()

代码解释:

  1. 导入 Matplotlib 库: import matplotlib.pyplot as plt
  2. 定义数据: monthssales 变量分别存储月份和对应月份的销售量。
  3. 绘制散点图: plt.scatter(months, sales, marker='x', color='blue') 使用 scatter 函数绘制散点图,并设置标识点为蓝色叉叉(marker='x', color='blue')。
  4. 添加图例: plt.legend(['Toothpaste'], loc='upper left') 使用 legend 函数添加图例,并将其放置在左上角(loc='upper left')。
  5. 添加图题: plt.title('图二:牙膏售卖量散点图') 使用 title 函数添加图题。
  6. 添加轴标签: plt.xlabel('Month Number')plt.ylabel('Number of Units Sold') 使用 xlabelylabel 函数添加 X 轴和 Y 轴标签。
  7. 添加背景网格: plt.grid(True, linestyle='-') 使用 grid 函数添加网格,并设置网格形式为横线(linestyle='-')。
  8. 显示图形: plt.show() 使用 show 函数显示绘制的散点图。

注意: 该代码需要在 Jupyter Notebook 或者其他支持 Matplotlib 的 Python 环境中运行。


原文地址: https://www.cveoy.top/t/topic/bP3b 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录