fork download
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3.  
  4. # 解决中文显示问题
  5. plt.rcParams['font.sans-serif'] = ['SimHei']
  6. plt.rcParams['axes.unicode_minus'] = False
  7.  
  8. # 示例数据:温度及对应三种物质的密度
  9. temperatures = np.array([0, 20, 40, 60, 80]) # 温度(℃)
  10. density_water = np.array([0.9998, 0.9982, 0.9922, 0.9832, 0.9718]) # 纯水密度
  11. density_ethanol = np.array([0.8062, 0.7893, 0.7725, 0.7549, 0.7365]) # 乙醇密度
  12. density_glycerol = np.array([1.2613, 1.2611, 1.2580, 1.2549, 1.2518]) # 甘油密度
  13.  
  14. bar_width = 0.25 # 柱子宽度
  15. x = np.arange(len(temperatures)) # X轴位置
  16.  
  17. # 绘制三组柱状图,错开排列避免重叠
  18. plt.bar(x - bar_width, density_water, width=bar_width, label='纯水', color='skyblue')
  19. plt.bar(x, density_ethanol, width=bar_width, label='乙醇', color='orange')
  20. plt.bar(x + bar_width, density_glycerol, width=bar_width, label='甘油', color='lightgreen')
  21.  
  22. # 设置图表信息
  23. plt.title('不同物质在多温度下的密度对比图', fontsize=14)
  24. plt.xlabel('温度(℃)', fontsize=12)
  25. plt.ylabel('密度(g/cm³)', fontsize=12)
  26. plt.xticks(x, temperatures) # X轴刻度对应温度值
  27. plt.legend() # 显示图例
  28.  
  29. # 为柱子添加数值标签
  30. for i, v in enumerate(density_water):
  31. plt.text(i - bar_width, v + 0.005, f'{v:.4f}', ha='center', fontsize=8)
  32. for i, v in enumerate(density_ethanol):
  33. plt.text(i, v + 0.005, f'{v:.4f}', ha='center', fontsize=8)
  34. for i, v in enumerate(density_glycerol):
  35. plt.text(i + bar_width, v + 0.005, f'{v:.4f}', ha='center', fontsize=8)
  36.  
  37. plt.tight_layout()
  38. plt.show()
  39.  
Success #stdin #stdout #stderr 1s 60304KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
/usr/local/lib/python3.7/dist-packages/matplotlib/font_manager.py:1241: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.
  (prop.get_family(), self.defaultFamily[fontext]))