-1

对于外面的人来说,这应该是一个非常简单的问题。我需要 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()

这是错误的情节,而不是我需要的

4

1 回答 1

2

首先我们创建样本数据

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 不是)。我们将其转换为 Dataframe:

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()

例子

于 2017-01-23T04:45:02.280 回答