pandas 如何为我的数据集创建多线图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45548415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a multi-line plot for my dataset?
提问by Dinosaurius
I have the following pandas DataFrame df
:
我有以下Pandas数据帧df
:
df = pd.DataFrame(columns=["Event1", "Event2", "Event3"],
data=[[15,1,22],
[16,1.26,80],
[27,0,15]])
df = df.set_index([["Series1", "Series2", "Series3"]])
I want to create a multiline plot with the X axis containing Event1
, Event2
and Event3
, while Y axis should be the corresponding numerical value. There should be 3 series: Series1
, Series2
, Series3
.
我想创建一个多线图,其中 X 轴包含Event1
,Event2
和Event3
,而 Y 轴应该是相应的数值。应该有 3 个系列:Series1
, Series2
, Series3
。
How can I define x
, y
and hue
in sns.pointplot(x=???, y=???, hue=???,data=df)
?
我如何定义x
,y
和hue
in sns.pointplot(x=???, y=???, hue=???,data=df)
?
plt.figure(figsize=(12,8))
ax = sns.pointplot(x=???, y=???, hue=???,data=df)
ax.grid(b=True, which='major', color='#d3d3d3', linewidth=1.0)
ax.grid(b=True, which='minor', color='#d3d3d3', linewidth=0.5)
plt.show()
回答by Serenity
Reorganize df which is pivot table to classic data frame and plot as you want:
将数据透视表 df 重新组织为经典数据框并根据需要绘制:
import matplotlib.pylab as plt
import pandas as pd
import seaborn as sns
df = pd.DataFrame(columns=["Event1", "Event2", "Event3"],
data=[[15,1,22],
[16,1.26,80],
[27,0,15]])
df = df.set_index([["Series1", "Series2", "Series3"]])
print(df)
# reorganize df to classic table
df2=df.stack().reset_index()
df2.columns = ['Series','Event','Values']
print(df2)
plt.figure(figsize=(12,8))
ax = sns.pointplot(x='Event', y='Values', hue='Series',data=df2)
ax.grid(b=True, which='major', color='#d3d3d3', linewidth=1.0)
ax.grid(b=True, which='minor', color='#d3d3d3', linewidth=0.5)
plt.show()
df2:
df2:
Series Event Values
0 Series1 Event1 15.00
1 Series1 Event2 1.00
2 Series1 Event3 22.00
3 Series2 Event1 16.00
4 Series2 Event2 1.26
5 Series2 Event3 80.00
6 Series3 Event1 27.00
7 Series3 Event2 0.00
8 Series3 Event3 15.00
回答by alec_djinn
I am not sure how to do it with seaborn but with matplolib it's something like this:
我不知道如何用 seaborn 来做,但是用 matplolib 是这样的:
for i in df.index.values:
plt.plot(list(df.loc[i]))
plt.show()
In this case, the X
ax will take value 0, 1 and 2 while the Y
ax will take the value of your rows. Just do plt.show()
at the end to have all plots in one figure. In seaborn should work pretty much in the same way.
在这种情况下,X
ax 将采用值 0、1 和 2,而Y
ax 将采用您的行的值。只需plt.show()
在最后将所有情节都放在一个数字中即可。在 seaborn 中应该以同样的方式工作。