使用matplotlib绘制多条线条
在本文中,我们将使用matplotlib库中的plot函数来展示多个年份的数据,每个年份将被绘制为一条线,并添加图例以区分不同的年份。
准备数据
首先,我们准备一些示例数据来展示,每个年份对应一个列表,例如:
import numpy as np
# 年份
years = [2010, 2011, 2012, 2013, 2014]
# 数据
data = {
2010: np.random.rand(10),
2011: np.random.rand(10),
2012: np.random.rand(10),
2013: np.random.rand(10),
2014: np.random.rand(10)
}
绘制图表
接下来,我们使用matplotlib中的plot函数来绘制多条线条,每个年份对应一条线,代码如下:
import matplotlib.pyplot as plt
# 创建画布
plt.figure(figsize=(10, 6))
# 绘制每个年份的数据
for year in years:
plt.plot(data[year], label=str(year))
# 添加图例
plt.legend()
# 添加标题和标签
plt.title('Data for Different Years')
plt.xlabel('Index')
plt.ylabel('Value')
# 显示图表
plt.show()
以上代码将绘制出每个年份对应的数据线,并在图表中添加图例以区分不同的年份。
运行结果
下图展示了使用matplotlib绘制出的多条线条图表:
[图表]
通过图表,我们可以清晰地看到每个年份的数据走势,同时也能方便地区分不同年份的数据线。这样的可视化效果有助于更直观地理解数据,分析数据之间的关系和趋势。matplotlib库提供了丰富的绘图功能,可以满足各种复杂可视化需求,帮助我们更好地展示和理解数据。