Matplotlib 盒图 + 图像显示(子图)

1 投票
1 回答
2374 浏览
提问于 2025-04-17 22:33

我正在做一些数据可视化的方法,其中一个是用箱线图来展示数据,代码如下:

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

用这段代码,我得到了下面的图像:

enter image description here

首先,我不明白为什么我的异常值没有显示为红色的加号,而是用标准的样式显示。此外,因为我想把箱线图和数据并排展示,所以我把绘图区域分开了。但是这个空间是平均分配的,导致图形效果很差。我希望箱线图占绘图区域的1/3,而数据占2/3。

谢谢大家!

1 个回答

2

这个错误其实是你在使用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)

nice plot

撰写回答