pandas groupby在同一地块上的结果 [英] Pandas groupby results on the same plot
问题描述
我正在处理以下数据框(仅用于说明,实际df很大):
I am dealing with the following data frame (only for illustration, actual df is quite large):
seq x1 y1
0 2 0.7725 0.2105
1 2 0.8098 0.3456
2 2 0.7457 0.5436
3 2 0.4168 0.7610
4 2 0.3181 0.8790
5 3 0.2092 0.5498
6 3 0.0591 0.6357
7 5 0.9937 0.5364
8 5 0.3756 0.7635
9 5 0.1661 0.8364
尝试绘制上述坐标的多条线图(x表示为"x1",y表示为"y1").
Trying to plot multiple line graph for the above coordinates (x as "x1 against y as "y1").
具有相同"seq"的行是一条路径,必须将其绘制为一条单独的线,就像与seq = 2对应的所有x,y坐标都属于一条线一样,依此类推.
Rows with the same "seq" is one path, and has to be plotted as one separate line, like all the x, y coordinates corresponding the seq = 2 belongs to one line, and so on.
我能够绘制它们,但是在单独的图形上,我希望使用 subplots 在同一图形上的所有线条,但并不能正确绘制.
I am able to plot them, but on a separate graphs, I want all the lines on the same graph, Using subplots, but not getting it right.
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib notebook
df.groupby("seq").plot(kind = "line", x = "x1", y = "y1")
这将创建100个图形(等于唯一序列的数量).为我提供一种获取同一图形上所有线条的方法.
This creates 100's of graphs (which is equal to the number of unique seq). Suggest me a way to obtain all the lines on the same graph.
**更新*
为解决上述问题,我实现了以下代码:
To resolve the above problem, I implemented the following code:
fig, ax = plt.subplots(figsize=(12,8))
df.groupby('seq').plot(kind='line', x = "x1", y = "y1", ax = ax)
plt.title("abc")
plt.show()
现在,我想要一种以特定颜色绘制线条的方法.我正在群集1中从seq = 2和5聚集路径;并从另一个群集中的seq = 3开始.
Now, I want a way to plot the lines with specific colors. I am clustering path from seq = 2 and 5 in cluster 1; and path from seq = 3 in another cluster.
因此,在群集1下有两行我要用红色表示,在群集2下有1行可以是绿色.
So, there are two lines under cluster 1 which I want in red and 1 line under cluster 2 which can be green.
我应该如何进行呢?
推荐答案
您需要在绘制本例之前先初始化轴
You need to init axis before plot like in this example
import pandas as pd
import matplotlib.pylab as plt
import numpy as np
# random df
df = pd.DataFrame(np.random.randint(0,10,size=(25, 3)), columns=['ProjID','Xcoord','Ycoord'])
# plot groupby results on the same canvas
fig, ax = plt.subplots(figsize=(8,6))
df.groupby('ProjID').plot(kind='line', x = "Xcoord", y = "Ycoord", ax=ax)
plt.show()
这篇关于 pandas groupby在同一地块上的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!