【问题标题】:How can I add a python's ggplot object to a matplot grid?如何将 python 的 ggplot 对象添加到 matplotlib 网格?
【发布时间】:2017-03-20 19:04:50
【问题描述】:

我的 pandas DataFrame results_print 有 2-dim 数组是图像。我像这样打印它们:

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 图像对象:

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 网格中?

【问题讨论】:

    标签: python matplotlib python-ggplot


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 2020-10-17
      • 2011-08-31
      • 2017-10-11
      相关资源
      最近更新 更多