Python Pandas绘制两个数据的直方图,但只有一个显示在直方图上。

3

我正在尝试绘制一个包含两个列的直方图,credit 和installments。 Credit只能是1或0(批准,不批准),而installments是每月支付的金额。

df=pn.read_csv(loc)
credit=df['credit.policy']
ins=df['installment']
     _,b,_=plt.hist(ins,bins='auto',label='credit=1',alpha=0.5,color='blue')
plt.hist(credit,bins=b,label='credit=0',alpha=0.5,color='red')
plt.legend(loc='best')
plt.ylim([0,700])
plt.show()

需要生成的图像

我需要生成类似下面这个的图像:

image2

[![新代码后的效果][3]][3]


1
如果credits始终为0或1,那么如何通过对其进行直方图处理来获得image2中的直方图呢?听起来你想要的是installments的两个直方图,一个是credits == 0时的直方图,另一个是credits == 1时的直方图。 - Michael
这个回答解决了你的问题吗?如何使用Matplotlib在直方图中按组填充颜色? - Patrick FitzGerald
2个回答

0
一个关于两个样本的直方图的简单示例可能会有所帮助:
import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)

mu, sigma = 100, 15
x1 = mu + sigma * np.random.randn(10000)
x2 = (mu + sigma * np.random.randn(10000))/2
# the histogram of the data
n, bins, patches = plt.hist([x1,x2], 50, density=True, alpha=0.75)


plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.xlim(40, 160)
plt.ylim(0, 0.03)
plt.grid(True)
plt.show()

请查看https://matplotlib.org/3.1.1/gallery/index.html以获取更多有关如何使用matplotlib的示例。
由于可能与堆叠图产生混淆,您要求的输出似乎较少见。

0

我决定创建两个列表,一个用于信用为0的客户,另一个用于信用为1的客户。

cred=[]
i0=[]
i1=[]
#df.hist(column='installment',bins='auto',label='credit=1',alpha=0.5,color='blue')
#df.hist(column='credit.policy',bins='auto',label='credit=1',alpha=0.5,color='red')
for i, row in credit.iteritems():
    cred.append(row)
for i, row in ins.iteritems():
    
    if cred[i]==1:
        i1.append(row)
    else:
        i0.append(row) 

plt.hist(i0,bins=75,color='blue',label='credit=0')
plt.hist(i1,bins=75,alpha=0.5,color='red',label='credit=1')
plt.legend()
plt.show()

image


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接