首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用matplotlib在一个子图中绘制熊猫DataFrame的两个直方图

使用matplotlib在一个子图中绘制熊猫DataFrame的两个直方图
EN

Stack Overflow用户
提问于 2018-08-08 22:28:07
回答 1查看 23.7K关注 0票数 12

我有一个熊猫数据框架,如下所示:

代码语言:javascript
复制
df = pd.DataFrame({ 'a_wood' : np.random.randn(100),
                 'a_grassland' : np.random.randn(100),
                 'a_settlement' : np.random.randn(100),
                 'b_wood' : np.random.randn(100),
                 'b_grassland' : np.random.randn(100),
                  'b_settlement' : np.random.randn(100)})

我想在一个子图中创建每个数据帧头的数据直方图。

代码语言:javascript
复制
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')

m=0
for i in range(2):
    for j in range(3):

        df.hist(column = df.columns[m], bins = 12, ax=ax[i,j], figsize=(20, 18))
        m+=1

为此,前面的代码运行得很好,但现在我想将每个a和b标题(例如"a_woods“和”b-wood“)组合到一个子图中,这样就只有三个直方图了。我尝试将两列赋值给df.columns[[m,m+3]],但这不起作用。我还有一个索引列,它包含像"day_1“这样的字符串,我希望它位于x轴上。有人能帮我吗?

这就是我所走的路。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-08 23:07:16

我不知道我是否正确理解了你的问题,但像这样的东西可以将情节结合起来。你可能想稍微玩玩alpha,然后改变头部。

代码语言:javascript
复制
#NOTE that you might want to specify your bins or they wont line up exactly
fig, ax = plt.subplots(1, 3, sharex='col', sharey='row', figsize=(20, 18))
n = 3
for j in range(n):
    df.hist(column=df.columns[j], bins=12, ax=ax[j], alpha=0.5, color='red')
    df.hist(column=df.columns[j+n], bins=12, ax=ax[j], alpha=0.5, color='blue')
    ax[j].set_title(df.columns[j][2:])

要将它们都绘制在彼此的旁边,请尝试以下命令:

代码语言:javascript
复制
#This example doesnt have the issue with different binsizes within one subplot
fig, ax = plt.subplots(1, 3, sharex='col', sharey='row', figsize=(20, 18))

n = 3
colors = ['red', 'blue']

axes = ax.flatten()
for i,j in zip(range(n), axes):
    j.hist([df.iloc[:,i], df.iloc[:,i+n]], bins=12, color=colors)
    j.set_title(df.columns[i][2:])

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51749208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档