来自 Pandas 的 Matplotlib 堆叠直方图被一条奇怪的线切割

Matplotlib stacked histogram from Pandas is being cut by a strange line

matplotlib 中发生了一些奇怪的事情。

我有一个 pandas 数据框,我正在使用它的两列制作堆叠直方图。一列是进入直方图箱的浮点数。另一列只有 0 和 1,用于将数据分成两个堆栈。我的实际代码有点复杂,但它是这样的:

print(df)

    df =
        col1    col2
        1.7       1
        2.4       0
        3.1       0
        4.0       1
        etc      etc

# First I separate the data by the 0's and 1's in col2
df_1 = df.loc[df['col2']==1]
df_0 = df.loc[df['col2']==0]
    fig, axes = 

使用 matplotlib 的直方图函数绘图可以正常工作。如果我这样称呼:

fig,axes= plt.subplots(nrows=1, ncols=1)

n,bins,patches= axes.hist( [ df_0['col1'], df_1['col1'] ] , histtype='step', stacked=True, Fill=True)

...我得到了这个非常好的情节:

但是,如果我在调用 hist() 时翻转 df_0 和 df_1 的顺序,就会发生一些非常奇怪的事情。 就像我这样做一样:

n,bins,patches= axes[0].hist( [ df_1['col1'], df_0['col1'] ] , histtype='step', stacked=True, Fill=True)

...我得到了一个堆栈翻转的情节(如预期的那样),但现在情节已经拿起了一个奇怪的神器;就像一条看不见的线,它正在切断并用颜色填充图形的某些地方。

这到底是怎么回事?我的第一个想法是 column1 或 column2 可能有 NaN 值或其他东西,但我检查了那些并且列值很好。关于可能导致此问题的原因有什么想法吗?

fill 不是 hist 的有用参数。这是一个有效的论点,因为您可以在 matplotlib 中填充任何补丁。但是,这里您没有要填充的封闭补丁。

您可能正在寻找 histogram_histtypes example 中显示的不同 histtype 选项。

  • histtype="stepfilled"
  • histtype='bar'

在这种情况下,他们都给出了相同的情节,

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np; np.random.seed(42)

a = np.random.rayleigh(size=20)
b = np.random.randn(20)+3
df = pd.DataFrame({"col1" : np.concatenate((a,b)),
                   "col2" : [0]*20 + [1]*20})

df_1 = df.loc[df['col2']==1]
df_0 = df.loc[df['col2']==0]

fig,axes= plt.subplots(ncols=2)

n,bins,patches= axes[0].hist([df_0['col1'], df_1['col1']], histtype='stepfilled', stacked=True)
n,bins,patches= axes[1].hist([df_0['col1'], df_1['col1']], histtype='bar', stacked=True)

plt.show()