Is it possible to plot multiline chart on Python ggplot?

允我心安 提交于 2019-12-09 13:46:16

问题


I need to plot 3 columns of a Pandas dataframe on python ggplot, with the same index. Is that possible?

Thank you


回答1:


I'm assuming you want something in ggplot that replicates something like this in 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.

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



回答2:


With the latest version of ggplot, it's even easier:

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



来源:https://stackoverflow.com/questions/24478925/is-it-possible-to-plot-multiline-chart-on-python-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!