How can I add a python's ggplot object to a matplot grid?

落爺英雄遲暮 提交于 2019-12-20 03:05:57

问题


My pandas DataFrame results_print has 2-dim arrays that are images. I print them like so:

n_rows = results_print.shape[0]
n_cols = results_print.shape[1]
f, a = plt.subplots(n_cols, n_rows, figsize=(n_rows, n_cols))
methods = ['img', 'sm', 'rbd', 'ft', 'mbd', 'binary_sal', 'sal']
for r in range(n_rows):
    for c, cn in zip(range(len(methods)), methods):
        a[c][r].imshow(results_print.at[r,cn], cmap='gray')

Now I created a python ggplot image object:

gg = ggplot(aes(x='pixels'), data=DataFrame({'pixels': results_print.at[6,'mbd'].flatten()})) + \
    geom_density(position='identity', stat='density') + \
    xlab('pixels') + \
    ylab('') + \
    ggtitle('Density of pixels') + \
    scale_y_log()

How can I add the gg as an element to my matplotlib grid?


回答1:


I think the solution would be to first draw the ggplot part. Then obtain the matplotlib figure object via plt.gcf() and the axes via plt.gca(). Resize the ggplot axes to fit into a grid and finally draw the rest of the matplotlib plots to that figure.

import ggplot as gp
import matplotlib.pyplot as plt
import numpy as np
# make ggplot
g = gp.ggplot(gp.aes(x='carat', y='price'), data=gp.diamonds)
g = g + gp.geom_point()
g = g + gp.ylab(' ')+ gp.xlab(' ')
g.make()
# obtain figure from ggplot
fig = plt.gcf()
ax = plt.gca()
# adjust some of the ggplot axes' parameters
ax.set_title("ggplot plot")
ax.set_xlabel("Some x label")
ax.set_position([0.1, 0.55, 0.4, 0.4])

#plot the rest of the maplotlib plots
for i in [2,3,4]:
    ax2 = fig.add_subplot(2,2,i)
    ax2.imshow(np.random.rand(23,23))
    ax2.set_title("matplotlib plot")
plt.show()


来源:https://stackoverflow.com/questions/42899779/how-can-i-add-a-pythons-ggplot-object-to-a-matplot-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!