【问题标题】:Matplotlib boxplot + imageshow (subplots)Matplotlib boxplot + imageshow(子图)
【发布时间】:2014-03-16 19:15:36
【问题描述】:

我正在做一些数据可视化的方法,其中一种是用该数据的箱线图显示数据,如下所示:

def generate_data_heat_map(data, x_axis_label, y_axis_label, plot_title, file_path, box_plot=False):
    plt.figure()
    plt.title(plot_title)
    if box_plot:
        plt.subplot(1, 2, 1)
        plt.boxplot(data.data.flatten(), sym='r+')
        plt.subplot(1, 2, 2)

    fig = plt.imshow(data.data, extent=[0, data.cols, data.rows, 0])
    plt.xlabel(x_axis_label)
    plt.ylabel(y_axis_label)
    plt.colorbar(fig)
    plt.savefig(file_path + '.png')
    plt.close()

使用此代码,这是我得到的图像:

首先,我不明白为什么我的传单没有用红色 + 表示,而是用标准模式表示。除此之外,因为我想并排绘制箱线图和数据,我划分了我的绘图区域。但是这个空间是平分的,人物情节变得非常糟糕。我希望箱线图占绘图区域的 1/3,数据占 2/3。

提前谢谢你。

【问题讨论】:

  • 你能发布你的情节吗?另外,你怎么称呼这个。如果您传递一个空的 Data 对象,那么您将没有要绘制的数据,而是零。
  • 对不起,@GraemeStuart。图像现在在那里。

标签: python matplotlib boxplot subplot


【解决方案1】:

该错误是您的 matplotlib 代码的一个简单错误。您正在绘制自己的图像。

你在哪里:

if box_plot:
    plt.subplot(1, 1, 1)
    plt.boxplot(data.data)
    plt.subplot(1, 2, 2)

您需要在对plt.subplots 的两次调用中指定子图的两行

这会起作用。

if box_plot:
    plt.subplot(1, 2, 1)
    plt.boxplot(data.data)
    plt.subplot(1, 2, 2)

如果您想独立调整绘图大小,则可以使用 gridspec.您可能希望像这样将它们绘制在彼此之上...

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec


def generate_data_heat_map(data, x_axis_label, y_axis_label, plot_title, file_path, box_plot=False):
    plt.figure()
    gs = gridspec.GridSpec(2, 1,height_ratios=[1,4])
    if box_plot:
        plt.subplot(gs[0])
        plt.boxplot(data.data.flatten(), 0, 'rs', 0)
        plt.subplot(gs[1])

    plt.title(plot_title)    
    fig = plt.imshow(data.data, extent=[0, data.cols, data.rows, 0])
    plt.xlabel(x_axis_label)
    plt.ylabel(y_axis_label)
    plt.colorbar(fig)
    plt.savefig(file_path + '.png')
    plt.close()

class Data(object):
    def __init__(self, rows=200, cols=300):
        # The data grid
        self.cols = cols
        self.rows = rows
        # The 2D data structure
        self.data = np.zeros((rows, cols), float)

    def randomise(self):
        self.data = np.random.rand(*self.data.shape)

data = Data()
data.randomise()
generate_data_heat_map(data, 'x', 'y', 'title', 'heat_map', box_plot=True)

【讨论】:

  • 是的,我现在才知道。但到目前为止,我无法按照自己的意愿划分空间。
  • 很抱歉打扰您,@GraemeStuart,但您知道如何更改箱线图的高度吗?输出的图像放到系统里太奇怪了,想想设计……
  • 我已调整代码以在两行上给出图,并使用 gridspec height_ratios 缩小箱线图。
  • 非常感谢您的宝贵时间。 (:
  • 正如我在您的示例中看到的,标题不再出现,@GraemeStuart?
猜你喜欢
  • 2015-11-30
  • 1970-01-01
  • 2021-10-27
  • 2021-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
相关资源
最近更新 更多