Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the plot generated from ggplot not showing up?

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?

like image 448
user4352158 Avatar asked Mar 29 '15 19:03

user4352158


People also ask

Why is my Ggplot not working?

3 if you see Error in ggplot(...) : could not find function "ggplot" , it means that the ggplot() function is not accessible because the package that contains the function ( ggplot2 ) was not loaded with library(ggplot2) . Thus you cannot use the ggplot() function without the ggplot2 package being loaded first.

Why is my Ggplot blank?

A blank ggplot is drawn. Even though the x and y are specified, there are no points or lines in it. This is because, ggplot doesn't assume that you meant a scatterplot or a line chart to be drawn.

How do I save a Ggplot graph?

If you are creating plots with ggplot, the best option is to use ggsave() and save the file with an EMF, PDF, or PNG extension, depending on how you would like to use it: Microsoft Word or PowerPoint (EMF), LaTeX editors (PDF), or other uses including sharing with colleagues (PDF or PNG).


1 Answers

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.

like image 112
LondonRob Avatar answered Oct 26 '22 13:10

LondonRob