1

I am trying to combine two approaches at creating histograms.

#Sample Data

df = pd.DataFrame({'V1':[1,2,3,4,5,6], 
         'V2': [43,35,6,7,31,34], 
         'V3': [23,75,67,23,56,32],
         'V4': [23,45,67,63,56,32],
        'V5': [23,5,67,23,6,2],
        'V6': [23,78,67,76,56,2],
        'V7': [23,45,67,53,56,32],
        'V8': [5,5,5,5,5,5],
        'cat': ["A","B","C","A","B","B"],})

I am able to create a histogram matrix for each category using this code.

 #1. Creating histogram matrix for each category 

for i in df['cat'].unique():
    fig, ax = plt.subplots()
    df[df['cat']==i].hist(figsize=(20,20),ax =ax)
    fig.suptitle(i + " Feature-Class Relationships", fontsize = 20)
    fig.savefig('Histogram Matrix.png' %(i), dpi = 240)

This creates a separate histogram matrix for each category. However what I would like is for the categories to be overlaid on the same matrix.

I am able to create an overlaid histogram using this approach:

#2. Overlaid histrogram for single variable

fig, ax = plt.subplots()
for i in df['cat'].unique():
    df[df['cat']==i]['V8'].hist(figsize=(12,8),ax =ax, alpha = 0.5, label = i)
ax.legend()
plt.show()

However this only creates a single overlaid image. I want to create an overlaid histogram for all of variables in the matrix i.e. all categories shown in the same matrix rather than a separate matrix for each category. I have created the following code, which is a combination of the above two approaches, but it does not overlay each of the histogram matrices together and only the last plot is created.

#3. Combining approaches to create a matrix of overlaid histograms

fig, ax = plt.subplots()
for i in df['cat'].unique():
    df[df['cat']==i].hist(figsize=(12,8),ax =ax, alpha = 0.5, label = i)
ax.legend()
fig.savefig('Combined.png', dpi = 240)

Is what I am trying to do possible?

1
  • 1
    I have severe problems in understanding and distinguishing the notions "matrix", "histogram matrix", "overlaid histogram", "overlaid image". Some of those seem to be the same, or maybe not? What is what? In any case that makes it quite hard to understand the actual problem, and more importantly what the desired output should look like. Oct 3, 2017 at 15:44

2 Answers 2

5

I guess this is what you want. A matrix of 2 columns and 4 rows and in each "cell" of this matrix you get the histogram for a column with the categories overlapped.

import pandas as pd
from matplotlib import pyplot as plt

df = pd.DataFrame({'V1':[1,2,3,4,5,6], 
         'V2': [43,35,6,7,31,34], 
         'V3': [23,75,67,23,56,32],
         'V4': [23,45,67,63,56,32],
        'V5': [23,5,67,23,6,2],
        'V6': [23,78,67,76,56,2],
        'V7': [23,45,67,53,56,32],
        'V8': [5,5,5,5,5,5],
        'cat': ["A","B","C","A","B","B"],})

# Define your subplots matrix.
# In this example the fig has 4 rows and 2 columns
fig, axes = plt.subplots(4, 2, figsize=(12, 8))

# This approach is better than looping through df.cat.unique
for g, d in df.groupby('cat'):
    d.hist(alpha = 0.5, ax=axes, label=g)

# Just outputing the legend for each column in fig
for c1, c2 in axes:
    c1.legend()
    c2.legend()

plt.show()

Here's the output:

subplots

0
1

The last code from the question should give you a warning about the axes being cleared - essentially the phenomenon you observe.

UserWarning: To output multiple subplots, the figure containing the passed axes is being cleared

Now the idea could be to let pandas plot each histogram in its own axes, but to make sure that each of those is the same, namely ax. This can be done by passing a list of 8 times ax, ax =[ax]*8:

fig, ax = plt.subplots(figsize=(12,8),)
for i in df['cat'].unique():
    df[df['cat']==i].hist(ax =[ax]*8, alpha = 0.5, label = i)
ax.legend()

plt.show()

The result will look very crowded, but this is apparently desired.
enter image description here

2
  • I'm sorry I wasn't clear. I should have added images to my question. Basically a histogram matrix is created for each variable when the .hist() method is called. In the first method I iterate through each category and this gives me a separate histogram matrix for each category. It would be more desirable if all the categories are on the same histogram matrix, which means overlaying the categories. The output provided by Arthur Gouvia, below, is what i was looking for.
    – alkey
    Oct 4, 2017 at 9:25
  • That was indeed not clear to me from the question. But if the other answer solves the problem, don't forget to accept it. Oct 4, 2017 at 9:28

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.