Question

I'm doing some methods for data visualization, being one of which to show the data with the box plot for this data, as follows:

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

With this code, this is the image that I get:

enter image description here

First of all, I didn't get why my fliers are not represented as red +, but with the standard pattern. Besides this, as I want to plot the box plot and the data side by side, I divided my plot area. But this space is equally divided, and the figure plot gets really bad. I would like that the box plot took some as 1/3 of the plot area, and the data 2/3.

Thank you in advance.

Was it helpful?

Solution

The error is a simple mistake with your matplotlib code. You are plotting over your own image.

Where you have:

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

you need to specify the two rows of your subplots in both calls to plt.subplots

This will work.

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

If you want to size the plots independently then you can use gridspec. You might want to plot them above one another like this...

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top