【问题标题】:how to plot 2 histograms side by side?如何并排绘制 2 个直方图?
【发布时间】:2017-12-17 14:22:11
【问题描述】:

我有 2 个数据框。我想并排绘制基于每个列“速率”的直方图。怎么办?

我试过这个:

import matplotlib.pyplot as plt
plt.subplot(1,2,1)

dflux.hist('rate' , bins=100) 
plt.subplot(1,2,2) 
dflux2.hist('rate' , bins=100) 
plt.tight_layout() 
plt.show() 

它没有达到预期的效果。它显示了两个空白图表,然后是一个填充图表。

【问题讨论】:

    标签: pandas matplotlib histogram


    【解决方案1】:

    使用subplots 定义具有两个轴的图形。然后使用ax 参数指定要在hist 内绘制的轴。

    fig, axes = plt.subplots(1, 2)
    
    dflux.hist('rate', bins=100, ax=axes[0])
    dflux2.hist('rate', bins=100, ax=axes[1])
    

    演示

    dflux = pd.DataFrame(dict(rate=np.random.randn(10000)))
    dflux2 = pd.DataFrame(dict(rate=np.random.randn(10000)))
    
    fig, axes = plt.subplots(1, 2)
    
    dflux.hist('rate', bins=100, ax=axes[0])
    dflux2.hist('rate', bins=100, ax=axes[1])
    

    【讨论】:

    • 成功了!我还发现在我所做的每件事上都设置了一个标题:axes[0].set_title('left title') 然后axes[1].set_title('right title')
    • @MarkGinsburg 您也可以在调用 hist 时使用 title 参数设置标题
    • 我试过这个dflux2.hist('rate' , bins=100, ax=axes[1], title='king') ,但语法错误,上面写着Unknown Property title
    • @MarkGinsburg 嗯,我猜我错了(-:幸好你想通了
    • @piRSquared,您是 Putnam 考试大师!:) 问题,如果我对 2 或 3 个散点图执行此操作,如何让它们彼此相邻?这是我目前拥有的代码:**bold [fig, axes = plt.subplots(1,2) plt.xlim(0,2000000) plt.ylim(0,250000) ax.scatter(Sales_Force_Before_Merger.Revenues[ Booked], Sales_Force_Before_Merger.Amount[Booked], alpha=0.05, color='g') ax.set_title("Revenue vs Amount for Booked Before Merger") ax.set_xlabel("Revenue", size = 10) ax.set_ylabel( "数量", size = 10) ax.plt.xticks(fontsize=10) ax.plt.show(ax=axes[0])] **
    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 2016-01-08
    • 2020-08-24
    • 2019-07-28
    • 2014-12-22
    相关资源
    最近更新 更多