matplotlib直方图矩阵,使用Pandas,覆盖多个类别

时间:2017-10-03 15:16:55

标签: python pandas matplotlib histogram

我正在尝试将两种方法结合起来创建直方图。

paintComponent()

我可以使用此代码为每个类别创建直方图矩阵。

#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"],})

这为每个类别创建了一个单独的直方图矩阵。但是我想要的是将类别重叠在同一个矩阵上。

我可以使用这种方法创建重叠的直方图:

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

然而,这只会创建一个叠加的图像。我想为矩阵中的所有变量创建一个重叠的直方图,即所有类别都显示在同一矩阵中,而不是每个类别的单独矩阵。 我创建了以下代码,它是上述两种方法的组合,但它没有将每个直方图矩阵重叠在一起,只创建了最后一个绘图。

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

我想做的是什么?

2 个答案:

答案 0 :(得分:2)

我想这就是你想要的。一个2列4行的矩阵,在该矩阵的每个“单元格”中,您可以获得具有重叠类别的列的直方图。

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

这是输出:

subplots

答案 1 :(得分:0)

问题的最后一个代码应该会给你一个关于轴被清除的警告 - 基本上是你观察到的现象。

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

现在的想法可能是让大熊猫在自己的轴上绘制每个直方图,但要确保每个直方图都是相同的,即ax。这可以通过传递8次axax =[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()

结果看起来非常拥挤,但这显然是需要的 enter image description here

相关问题