pandas 是否可以在 Python ggplot 上绘制多折线图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24478925/
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
Is it possible to plot multiline chart on Python ggplot?
提问by Hugo
I need to plot 3 columns of a Pandas dataframe on python ggplot, with the same index. Is that possible?
我需要在 python ggplot 上用相同的索引绘制 Pandas 数据框的 3 列。那可能吗?
Thank you
谢谢
回答by chrisb
I'm assuming you want something in ggplot that replicates something like this in matplotlib.
我假设你想要在 ggplot 中的一些东西在 matplotlib 中复制这样的东西。
import pandas as pd
df = pd.DataFrame({'a': range(10), 'b': range(5,15), 'c': range(7,17)})
df.plot()
ggplot expects the data to be in 'long' format, so you need to do a little reshaping, with melt. It also currently does not support plotting the index, so that needs to made into a column.
ggplot 期望数据为“长”格式,因此您需要使用melt. 它目前也不支持绘制索引,因此需要制作成一列。
from ggplot import ggplot, geom_line, aes
import pandas as pd
df = pd.DataFrame({'a': range(10), 'b': range(5,15), 'c': range(7,17)})
df['x'] = df.index
df = pd.melt(df, id_vars='x')
ggplot(aes(x='x', y='value', color='variable'), df) + \
geom_line()
回答by Contango
With the latest version of ggplot, it's even easier:
使用最新版本的 ggplot,更简单:
from ggplot import ggplot, geom_line, aes
import pandas as pd
df = pd.DataFrame({'a': range(10), 'b': range(5, 15), 'c': range(7, 17)})
df['x'] = df.index
ggplot(aes(x='x'), data=df) +\
geom_line(aes(y='a'), color='blue') +\
geom_line(aes(y='b'), color='red') +\
geom_line(aes(y='c'), color='green')


