通过add_subplot添加子图后如何共享轴? [英] How to share axes after adding subplots via add_subplot?

查看:420
本文介绍了通过add_subplot添加子图后如何共享轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框:

I have a dataframe like this:

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))     

    A    B    C    D
a  0.3  0.1  0.2  0.6
b  0.2  0.0  0.5  0.3
c  0.5  0.3  0.0  0.4
d  0.2  0.1  0.7  0.6

现在,我想将每行绘制为条形图,从而使用add_subplot共享y轴和x-tick标签.

Now I want to plot each row as a barplot whereby the y-axis and the x-tick-labels are shared using add_subplot.

直到现在,我只能生成如下图:

Until now, I can only produce a plot that looks like this:

有一个问题:

轴不共享,使用add_subplot后怎么做? 此处,此问题通过创建一个巨大的子图得以解决;有什么办法可以以不同的方式做到这一点吗?

The axes are not shared, how one do this after using add_subplot? Here, this problem is solved by creating one huge subplot; is there any way to do this in a different manner?

我想要的结果看起来像上面的图,唯一的不同是,上排没有x-tick标签,而右栏中没有y-tick标签.

My desired outcome looks like the plot above with the only difference, that there are no x-tick-labels in the upper row and now y-tick-labels in the right column.

我当前的尝试如下:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))

fig = plt.figure()
bar_width = 0.35
counter = 1
index = np.arange(df.shape[0])

for indi, rowi in df.iterrows():

    ax = fig.add_subplot(2, 2, counter)
    ax.bar(index, rowi.values, width=bar_width, tick_label=df.columns)
    ax.set_ylim([0., 1.])
    ax.set_title(indi, fontsize=20)
    ax.set_xticks(index + bar_width / 2)
    counter += 1

plt.xticks(index + bar_width / 2, df.columns)

推荐答案

如何在matplotlib中生成共享子图的问题:

The question how to produce shared subplots in matplotlib:

  • The SO seach engine results
  • The matplotlib recipes or the examples page

在这里可能更有趣的是,您还可以直接使用熊猫在一行中创建图:

What may be more interesting here, is that you could also directly use pandas to create the plot in a single line:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))
df.plot(kind="bar", subplots=True, layout=(2,2), sharey=True, sharex=True)
plt.show()

这篇关于通过add_subplot添加子图后如何共享轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆