简体   繁体   English

Python ggplot:是否可以关闭显示的GUI? 获取命令行(“非交互式绘图”/“批处理”)

[英]Python ggplot: Is it possible to turn off the GUI displayed? and get a command-line (“non-interactive plotting”/“batch”)

When plotting with Python ggplot, every single plot command causes a GUI pane to be displayed and suspend execution ("interactive plotting"). 使用Python ggplot绘图时,每个绘图命令都会显示一个GUI窗格并暂停执行(“交互式绘图”)。 But I want to: 但是我要:

  1. avoid/ turn off this GUI and save the plot object some where in runtime (I will be displaying it in some other C# forms control). 避免/关闭此GUI并将绘图对象保存在运行时的某些位置(我将在其他一些C#表单控件中显示它)。

  2. find a Python equivalent to dev.off() command in R language which turns off the GUI for plotting. 在R语言中找到一个等效于dev.off()命令的Python,它关闭了用于绘图的GUI。

Example: 例:

print ggplot(data, aes('Age', 'Weight')) + geom_point(colour='steelblue') 

When I execute this, it opens up a new GUI (like below) displaying the plot. 当我执行它时,它会打开一个显示图表的新GUI(如下所示)。

在此输入图像描述

Since plotting is triggered by __repr__ method the obvious approach is to avoid situations when it is called. 由于绘图是由__repr__方法触发的,显而易见的方法是避免调用它时的情况。 Since you want to use this plot in some other place there is no reason to call print or even executing statements which will be discarded like this: 由于你想在其他地方使用这个图,所以没有理由调用print或甚至执行将被丢弃的语句,如下所示:

ggplot(data, aes('Age', 'Weight')) + geom_point(colour='steelblue') 

Instead you can simply assign it to the variable 相反,您可以简单地将其分配给变量

p = ggplot(data, aes('Age', 'Weight')) + geom_point(colour='steelblue') 

what is exactly the same thing one would do in R. Using graphic device to redirect output and discarding it doesn't really make sense. 在R中做什么是完全一样的。使用图形设备重定向输出并丢弃它并不是真的有意义。

If for some reason that's not enough you switch to non-interactive matplotlib backend: 如果由于某种原因这还不够,你可以切换到非交互式matplotlib后端:

import matplotlib
matplotlib.use('Agg')
from ggplot import *
ggplot(aes(x='date', y='beef'), data=meat)
<ggplot: (...)>

You can do the following, which returns a matplotlib figure: 您可以执行以下操作,返回matplotlib图:

g = ggplot(...) + geom_xxx(...)
fig = g.draw()

ggplots __repr__() method (what is called by print(g) is basically self.draw() then use matplotlibs plt.show() to show the plot... ggplots __repr__()方法( print(g)调用的基本上是self.draw()然后使用matplotlibs plt.show()来显示图...

You can also use ggsave(g) to save the plot somewhere. 您还可以使用ggsave(g)将绘图保存在某处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM