简体   繁体   English

是否有可能在Python ggplot上绘制多线图?

[英]Is it possible to plot multiline chart on Python ggplot?

I need to plot 3 columns of a Pandas dataframe on python ggplot, with the same index. 我需要在python ggplot上绘制3列Pandas数据帧,并使用相同的索引。 Is that possible? 那可能吗?

Thank you 谢谢

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 . ggplot期望数据采用“长”格式,所以你需要做一些重塑, melt It also currently does not support plotting the index, so that needs to made into a column. 它目前还不支持绘制索引,因此需要将其制作成列。

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

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

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM