简体   繁体   中英

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"). 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).

  2. find a Python equivalent to dev.off() command in R language which turns off the GUI for plotting.

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.

在此输入图像描述

Since plotting is triggered by __repr__ method the obvious approach is to avoid situations when it is called. 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:

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.

If for some reason that's not enough you switch to non-interactive matplotlib backend:

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:

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...

You can also use ggsave(g) to save the plot somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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