如何将python的ggplot对象添加到matplot网格? [英] How can I add a python's ggplot object to a matplot grid?

查看:202
本文介绍了如何将python的ggplot对象添加到matplot网格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的熊猫DataFrame results_print具有二维图像数组.我这样打印它们:

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')

现在,我创建了一个python ggplot图像对象:

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()

如何将gg作为元素添加到matplotlib网格中?

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

推荐答案

我认为解决方案是先绘制ggplot部分.然后通过plt.gcf()获取matplotlib图形对象,并通过plt.gca()获取轴.调整ggplot轴的大小以适合网格,最后将其余的matplotlib图绘制到该图.

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()

这篇关于如何将python的ggplot对象添加到matplot网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆