import matplotlib.pyplot as plt
import pandas as pd

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['axes.unicode_minus'] = False

# 数据
data = {
    'month_number': list(range(1, 13)),
    'facecream': [2500, 2630, 2140, 3400, 3600, 2760, 2980, 3700, 3540, 1990, 2340, 2900],
    'facewash': [1500, 1200, 1340, 1130, 1740, 1555, 1120, 1400, 1780, 1890, 2100, 1760],
    'toothpaste': [5200, 5100, 4550, 5870, 4560, 4890, 4780, 5860, 6100, 8300, 7300, 7400],
    'bathingsoap': [9200, 6100, 9550, 8870, 7760, 7490, 8980, 9960, 8100, 10300, 13300, 14400],
    'shampoo': [1200, 2100, 3550, 1870, 1560, 1890, 1780, 2860, 2100, 2300, 2400, 1800],
    'moisturizer': [1500, 1200, 1340, 1130, 1740, 1555, 1120, 1400, 1780, 1890, 2100, 1760],
    'total_units': [21100, 18330, 22470, 22270, 20960, 20140, 29550, 36140, 23400, 26670, 41280, 30020],
    'total_profit': [211000, 183300, 224700, 222700, 209600, 201400, 295500, 361400, 234000, 266700, 412800, 300200]
}
df = pd.DataFrame(data)

# 创建图形
plt.figure(figsize=(10, 6))

# 绘制直方图
df['total_profit'].plot.hist(bins=10, density=True, alpha=0.7, edgecolor='black', color='blue')

# 绘制密度曲线
df['total_profit'].plot.kde(color='orange')

# 添加图例和标题
plt.legend(['Distribution Density', 'Frequency Counts'])
plt.title('图五:售卖额条形分布图')

# 添加轴标签
plt.xlabel('Profit Range in dollar')
plt.ylabel('Frequency Counts')

# 显示图形
plt.show()

这段代码使用Matplotlib库绘制了销售额数据的直方图和密度曲线。

代码解释:

  1. 导入必要的库: 导入matplotlib.pyplot和pandas库。
  2. 设置中文字体: 确保图形中能够正确显示中文。
  3. 创建数据: 使用字典创建示例数据,并将其转换为Pandas DataFrame。
  4. 创建图形: 使用plt.figure()创建一个新的图形,并使用figsize参数设置图形大小。
  5. 绘制直方图: 使用df['total_profit'].plot.hist()绘制销售额数据的直方图。
  6. 绘制密度曲线: 使用df['total_profit'].plot.kde()绘制销售额数据的密度曲线。
  7. 添加图例和标题: 使用plt.legend()添加图例,使用plt.title()添加标题。
  8. 添加轴标签: 使用plt.xlabel()和plt.ylabel()添加x轴和y轴标签。
  9. 显示图形: 使用plt.show()显示生成的图形。

通过这段代码,你可以学习如何使用Matplotlib库创建直方图和密度曲线,以便更好地理解和分析数据的分布情况。

Python数据可视化:使用Matplotlib绘制直方图和密度曲线

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

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