如何在 python 中使用多条线绘制一个图形
How to plot one figure with multiple lines in python using
对于外面的人来说,这应该是一个非常简单的问题。我需要 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()
首先我们创建示例数据
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()
对于外面的人来说,这应该是一个非常简单的问题。我需要 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()
首先我们创建示例数据
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()