我一直在尝试使用plotnine 进行绘图,据我所知,它是Python 中最像ggplot2 风格的库,但我在Python 脚本中的PyCharm 中很难完成它。这似乎是一个问题,对于 matplotlib 和其他也遇到此错误的绘图库有许多解决方案,但使用他们的答案(将
DISPLAY=True
添加到环境变量,在绘图末尾添加 show()
等)不起作用对于情节。
我正在尝试绘制以下内容,它在常规 ipython 窗口中工作(我通过终端访问):
from plotnine import *
from plotnine.data import *
(ggplot(diamonds)
+ stat_summary(aes('clarity', 'price', fill='cut'), geom='col', position='dodge')
+ stat_summary(aes('clarity', 'price', color='cut'), geom='linerange', size=1, position=position_dodge(width=0.9))
+ scale_color_hue(l=.3)
+ theme(figure_size=(11, 8))
)
我在这里错过了什么,或者我不应该尝试从脚本中进行绘图,这通常对其他一切都很方便?
附注解决方案:这似乎是 PyCharm 中的一个错误,社区可能还没有注意到,但这有点公平,因为plotnine 库也有点新。我的解决方案是避免尝试在脚本中执行此操作,而是从 PyCharm 中的 ipython 控制台内进行绘图,这是有效的。
你必须打印 ggplot 对象。
p = (ggplot(diamonds)
+ stat_summary(aes('clarity', 'price', fill='cut'), geom='col', position='dodge')
+ stat_summary(aes('clarity', 'price', color='cut'), geom='linerange', size=1, position=position_dodge(width=0.9))
+ scale_color_hue(l=.3)
+ theme(figure_size=(11, 8))
)
print(p)
IPython 自动为您打印单元格中的最后结果。对于其他环境,您必须明确地执行此操作
我今天遇到了同样的问题,人工智能等不知道,按照其他地方的建议打印没有任何作用。有效的方法是将 True 添加到 draw() 语句中。
plot = ggplot(df, aes('column1', 'column2')) + geom_line()
plot.draw(True)