10

I am unable to display the plot from ggplot. I've tried something like

import pandas as pd
import pylab as plt
import statsmodels.api as sm
from ggplot import *

df = pd.DataFrame.from_csv('file.csv', index_col=None)
x=df['X']
y=df['Y']
plt=ggplot(data=df,aes(x=x, y=y)) +\
    geom_line() +\
    stat_smooth(colour='blue', span=0.2)
plt.show()

Why is it not showing up?

LondonRob
  • 73,083
  • 37
  • 144
  • 201
user4352158
  • 731
  • 4
  • 13
  • 24
  • I'm pretty sure that there is an error message: can you show it? – Jan Katins Mar 29 '15 at 22:08
  • Also: I think that it should be g = ggplot(...) + ...; g.draw(); plt.show() – Jan Katins Mar 29 '15 at 22:09
  • if I try that I get the error `g=ggplot(data=df,aes(x=x, y=y)) +\ SyntaxError: non-keyword arg after keyword arg Process finished with exit code 1` – user4352158 Mar 30 '15 at 03:44
  • I am not sure about this but does ggplot have a show() method ? I have only used show() method from pyplot (matplotlib). import matplotlib.pyplot as plt. What do you get when you type plt or print plt ? – Amrita Sawant Mar 30 '15 at 05:06

1 Answers1

11

The line plt = ggplot(.... is not right, for a few reasons.

  1. plt is the name you've given the pylab module. plt = will delete it!
  2. data=df is a keyword argument (because of the data= part). They have to go after positional arguments. See the keyword entry of the Python glossary for details. You either need to make the first argument positional by taking out data=, or put it after the positional argument aes(x=x, y=y).
  3. the ggplot call returns a ggplot object, not a pyplot-related thing. ggplot objects have draw() not show().

The developer himself shows here how it's meant to be done:

g = ggplot(df, aes(x=x, y=y)) +\
    geom_line() +\
    stat_smooth(colour='blue', span=0.2)
print(g)
# OR
g.draw()

That last line g.draw() returns a matplotlib figure object so you can also do:

fig = g.draw()

which will give you access to the matplotlib figure, if that's the sort of thing you want to do.

Community
  • 1
  • 1
LondonRob
  • 73,083
  • 37
  • 144
  • 201
  • 2
    This was useful to me, except I found that the draw() method doesn't exist (at least with the ggplot-0.11.5-py35_1 that appears to be current). Instead, the method is show(). Also, show() does not return anything, so you can't easily get the matplotlib figure in the manner you described. – ybull Apr 27 '17 at 15:09
  • @ybull: Same here – Make42 Sep 07 '17 at 10:53