【问题标题】:python pandas plotting two data's but only one shows on the histogrampython pandas 绘制两个数据,但直方图上只显示一个
【发布时间】:2020-09-29 01:10:37
【问题描述】:

我正在尝试绘制包含两列信用和分期付款的直方图。 credit 只能是 1 或 0(已批准,未批准),而分期付款是他们每月支付的金额。

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

我需要制作的图像是这样的

[![在新代码之后][3]][3]

【问题讨论】:

  • 如果 credits 总是 0 或 1,那么直方图怎么会给你 image2 中的直方图呢?听起来您想要的是 2 个分期付款的直方图,一个是 credits == 0,另一个是 credits == 1

标签: python pandas matplotlib plot


【解决方案1】:

两个样本的直方图的简单示例可能会有所帮助:

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

有关如何使用matplotlib 的更多示例,请参阅https://matplotlib.org/3.1.1/gallery/index.html

由于可能与堆叠图混淆,您要求的输出似乎不太常见。

【讨论】:

    【解决方案2】:

    我决定为 credit=0 和 credit=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()
    

    【讨论】:

      猜你喜欢
      • 2015-01-10
      • 2017-08-13
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      相关资源
      最近更新 更多