python ggplot is great, but still new, and I find the need to fallback on traditional matplotlib techniques to modify my plots. But I'm not sure how to either pass an axis instance to ggplot, or get one back from it.
So let's say I build a plot like so:
import ggplot as gp
(explicit import)
p = gp.ggplot(gp.aes(x='basesalary', y='compensation'), data = df)
p + gp.geom_histogram(binwidth = 10000)
No problems so far. But now let's say I want the y-axis in log scale. I'd like to be able to do this:
plt.gca().set_yscale('log')
Unfortunately, plt.gca()
doesn't access the axis created by ggplot
. I end up with two figures: the histogram from ggplot in linear scale, and an empty figure with a log-scale y axis.
I've tried a few variations with both gca()
and gcf()
without success.
Did you try:
Not sure if it works just like that though, just guessing from looking at the code...
There might have been some changes since 2013 when this question was asked. The way to produce a matplotlib figure from a ggplot is
after that, figure and axes can be obtained via
or, if there are more axes,
axes = fig.axes
.Then, additional features can be added in matplotlib, like also shown in this question's answer.
Finally the plot can be saved using the usual
savefig
command.Complete example:
[This is outdated with current ggpy]
There is now a
scale_y_log()
. If you want to do something inmatplotlib
, you can get the current figure/axis withYour version fails because ggplots draws the plot on
print(g)
in theggplot.__repr__()
method (which callsggplot.draw()
), so there is simple nomatplotlib
figure right after constructing the ggplot object but only afterprint
(org.draw()
).g.draw()
also returns the figure, so you don't need to useplt.gcf()