对于那里的人来说,这应该是一个非常简单的问题。我需要python中的线图,其中自变量(x轴)是Date
。 y轴是从属Value
数据,并且会有多行:每Name
一行,用于描述Value
随时间的变化。除了使用matplotlib之外,我不确定如何做到这一点。
这就是我在df
中整理数据的方式,它将数据从csv文件中提取出来。
Name = df['Name']
Value = df['expected harvest (Value)']
Date = df['Date']
result = pd.concat([Name, Value, Date], axis=1)
>>> result
Name Value Date
1 189 9.0 11/14/15
2 191 10.0 11/14/15
3 192 1.0 11/14/15
4 193 4.0 11/14/15
... ... ... ...
2948 189 7.0 2/20/16
2950 190 1.0 2/20/16
2952 191 3.0 2/20/16
2953 192 3.0 2/20/16
2954 193 0.0 2/20/16
到目前为止,我已尝试过此操作,但我需要将线条设置为水平线而不是垂直线,并为每个Name
分别设置线条。不知怎的,我错过了如何按Name
对数据进行分组,然后绘制为单独的行。
fig = plt.figure()
ax = fig.add_subplot(111)
x_points = df['Date']
x_points = pd.to_datetime(x_points)
y_points = df['expected harvest (Value)']
p = ax.plot(x_points, y_points, 'b')
ax.set_xlabel('x-points')
ax.set_ylabel('y-points')
ax.set_title('Simple XY point plot')
fig.show()
答案 0 :(得分:1)
首先我们创建样本数据
sample_dates = ['1/1/15', '1/2/15', '1/3/15', '1/4/15']
dates = []
for date in sample_dates:
[dates.append(date) for _ in range(4)]
values = np.random.randint(1, 8, size=15)
names = [1, 2, 3, 4] * 4
我们在中间删除了一些(如190中没有的示例数据)。我们将其转换为数据帧:
names.pop(6)
dates.pop(6)
x_date = pd.to_datetime(dates)
df = pd.DataFrame()
df['names'] = names
df['values'] = values
df['dates'] = x_date
现在我们按名称走他们,我们绘制它们
for i in df.names.unique():
x = df[df.names==i]['dates']
y = df[df.names==i]['values']
plt.plot(x, y)
plt.show()