下面是一个使用Python和Matplotlib库的示例代码,可以将数据按列值分组绘制成多线的图表。
import pandas as pd
import matplotlib.pyplot as plt
# 创建示例数据
data = {'Year': [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019],
'Group1': [5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
'Group2': [8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
'Group3': [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]}
df = pd.DataFrame(data)
# 设置图表样式
plt.style.use('seaborn-darkgrid')
# 绘制图表
fig, ax = plt.subplots()
# 按列值分组绘制多线的图表
for column in df.columns[1:]:
ax.plot(df['Year'], df[column], marker='o', label=column)
# 添加图例
ax.legend()
# 设置标题和轴标签
ax.set_title('Column Value Grouped Line Chart')
ax.set_xlabel('Year')
ax.set_ylabel('Value')
# 显示图表
plt.show()
这段代码首先创建了一个包含Year、Group1、Group2和Group3列的示例数据。然后,使用Matplotlib库来绘制图表。代码中的plt.style.use('seaborn-darkgrid')
用于设置图表的样式。
然后,通过使用subplots()
函数创建一个新的图表和一个子图。接下来,使用一个循环来遍历数据框的每一列(除了Year列),并使用plot()
函数绘制每一列的数据作为一条线。marker='o'
参数用于在线上标记数据点。然后,使用legend()
函数添加图例。
最后,使用set_title()
、set_xlabel()
和set_ylabel()
函数设置图表的标题和轴标签。
最后一行的plt.show()
用于显示图表。执行代码后,将会显示一个包含多条线的图表,每条线对应数据框中的一列,Year列作为x轴的值。
上一篇:按列值分组的 Antd 树形表
下一篇:按列值分组拼接行