【问题标题】:Why is the plot generated from ggplot not showing up?为什么 ggplot 生成的图没有显示出来?
【发布时间】:2015-06-02 18:03:10
【问题描述】:

我无法显示来自ggplot 的绘图。我试过类似的东西

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

为什么不显示?

【问题讨论】:

  • 我很确定有错误信息:你能显示吗?
  • 另外:我认为应该是 g = ggplot(...) + ...; g.draw(); plt.show()
  • 如果我尝试得到错误g=ggplot(data=df,aes(x=x, y=y)) +\ SyntaxError: non-keyword arg after keyword arg Process finished with exit code 1
  • 我不确定,但 ggplot 有 show() 方法吗?我只使用了 pyplot (matplotlib) 中的 show() 方法。将 matplotlib.pyplot 导入为 plt。当你输入 plt 或 print plt 时你会得到什么?

标签: python python-3.x ggplot2 python-ggplot


【解决方案1】:

plt = ggplot(.... 行不正确,有几个原因。

  1. plt 是您为 pylab 模块指定的名称。 plt = 会删除它!
  2. data=df 是一个关键字参数(因为 data= 部分)。他们必须位置参数之后。有关详细信息,请参阅the keyword entry of the Python glossary。您要么需要通过取出data= 使第一个参数具有位置性,要么将其放在位置参数aes(x=x, y=y) 之后。
  3. ggplot 调用返回一个ggplot 对象,而不是一个与pyplot 相关的东西。 ggplot 对象有draw() 而不是show()

开发者本人向here展示了它是如何完成的:

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

最后一行 g.draw() 返回一个 matplotlib 图形对象,因此您也可以这样做:

fig = g.draw()

这将使您能够访问matplotlib 图,如果这是您想做的事情。

【讨论】:

  • 这对我很有用,除了我发现 draw() 方法不存在(至少 ggplot-0.11.5-py35_1 似乎是最新的)。相反,该方法是 show()。此外, show() 不返回任何内容,因此您无法以您描述的方式轻松获取 matplotlib 图。
  • @ybull:这里也一样
猜你喜欢
  • 1970-01-01
  • 2018-12-27
  • 1970-01-01
  • 2017-06-05
  • 2015-01-18
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 2020-10-30
相关资源
最近更新 更多