探索数据可视化的美妙世界
基于原教程的matplotlib示例,转换为交互式网页图表
# 绘制折线图
import matplotlib.pyplot as plt
import numpy as np
# 数据准备
days = np.arange(4, 19)
max_temps = np.array([32, 33, 34, 34, 33, 31, 30, 29, 30, 29, 26, 23, 21, 25, 31])
min_temps = np.array([19, 19, 20, 22, 22, 21, 22, 16, 18, 18, 17, 14, 15, 16, 16])
# 绘制图表
plt.plot(days, max_temps, label='最高气温', color='red', linewidth=2)
plt.plot(days, min_temps, label='最低气温', color='blue', linewidth=2)
# 添加标签和标题
plt.xlabel('日期')
plt.ylabel('温度 (°C)')
plt.title('未来15天最高气温和最低气温')
plt.legend()
plt.grid(True, alpha=0.3)
# 显示图表
plt.show()
# 绘制柱形图
import matplotlib.pyplot as plt
import numpy as np
# 数据准备
categories = ['a', 'b', 'c', 'd', 'e']
values1 = np.array([10, 8, 7, 11, 13])
values2 = np.array([9, 6, 5, 10, 12])
bar_width = 0.4
# 绘制分组柱状图
x = np.arange(len(categories))
plt.bar(x, values1, tick_label=categories, width=bar_width,
color='skyblue', label='系列1')
plt.bar(x + bar_width, values2, width=bar_width,
color='salmon', label='系列2')
# 添加标签和标题
plt.xlabel('类别')
plt.ylabel('数值')
plt.title('分组柱状图示例')
plt.legend()
# 显示图表
plt.show()
# 绘制误差条形图
import matplotlib.pyplot as plt
import numpy as np
# 数据准备
x = np.arange(5)
y = np.array([10, 8, 7, 11, 13])
error = [2, 1, 2.5, 2, 1.5]
# 绘制误差条形图
plt.errorbar(x, y, yerr=error, fmt='o',
color='blue', ecolor='red',
capsize=5, capthick=2,
markersize=8, markerfacecolor='yellow',
markeredgewidth=2)
# 添加标签和标题
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('误差条形图示例')
plt.grid(True, alpha=0.3)
# 显示图表
plt.show()
从基础到高级,逐步掌握Matplotlib
学习折线图、柱形图等基础图表的绘制方法
掌握颜色、字体、布局等图表美化技巧
学习子图、动画、3D图表等高级功能