matplotlib中发生了一些奇怪的事情。
我有一个熊猫数据框,我正在使用它的两个列进行堆叠直方图。一列是浮点数,进入直方图箱。另一列仅为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值或其他东西,但我检查了那些并且列值很好。关于可能导致这种情况的任何想法?
答案 0 :(得分:1)
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()