I came across this post, which detailed how to incorporate a ggplot
object into a matplotlib
grid. The process involves first generating a ggplot
object, getting the current figure, and then building more subplots onto the existing figure with the state-based API.
I wanted to replicate this using the object-oriented API in order to make this more extensible.
import ggplot as gp
import matplotlib.pyplot as plt
g = gp.ggplot(gp.aes(x='carat', y='price'), data=gp.diamonds) + gp.geom_point() + gp.ylab('price') + gp.xlab('carat')
g.make()
f1 = plt.gcf()
g = gp.ggplot(gp.aes(x='price', y='carat'), data=gp.diamonds) + gp.geom_point() + gp.ylab('carat') + gp.xlab('price')
g.make()
f2 = plt.gcf()
(fig, axes) = plt.subplots(1,2, figsize=(20,10))
axes[0] = f1.axes[0]
axes[0].set_title('Price vs. Carat')
axes[1] = f2.axes[0]
axes[1].set_title('Carat vs. Price')
fig.show()
However, when this is executed, the output comes out blank:
My motivation for this post extends beyond just the ggplot
library, as ideally I'd like to create grids using graphics from several different libraries like seaborn
or bokeh
too. What is the best way to extract an axis from a graph and add it onto a matplotlib
figure grid using the object-oriented API?
EDIT: As @ImportanceOfBeingErnest suggested, I tried a different method:
import ggplot as gp
import matplotlib.pyplot as plt
g = gp.ggplot(gp.aes(x='carat', y='price'), data=gp.diamonds) + gp.geom_point() + gp.ylab('price')+ gp.xlab('carat')
g.make()
f1 = plt.gcf()
g = gp.ggplot(gp.aes(x='price', y='carat'), data=gp.diamonds) + gp.geom_point() + gp.ylab('carat')+ gp.xlab('price')
g.make()
f2 = plt.gcf()
plt.show()
def add_axis(fig, ggFig, pos):
ggAxis = ggFig.axes[0]
ggAxis.remove()
ggAxis.figure = fig
fig.axes.append(ggAxis)
fig.add_axes(ggAxis)
dummy = fig.axes[pos]
ggAxis.set_position(dummy.get_position())
dummy.remove()
plt.close(ggFig)
(fig, axes) = plt.subplots(1,2, figsize=(20,10))
add_axis(fig, f2, 1)
add_axis(fig, f1, 0)
fig.show()
Oddly enough, this works if add_axis is called with pos=1 and then pos=0, but not the other way around. Why might this be?