简体   繁体   English

将相同的x轴标签传递给条形图的matplotlib子图

[英]Passing same x axis label to matplotlib subplots of barplots

I'm trying to create subplots of barplots. 我正在尝试创建条形图的子图。 matplotlib is funny with labeling the x axis of barplots so you need to pass an index then use the xticks function to pass the labels. matplotlib很有趣,它标记了条形图的x轴,所以你需要传递一个索引然后使用xticks函数来传递标签。 I want to create 2 subplots that each have the same x axis labels but with the code below I can only pass the labels onto the last bar plot. 我想创建2个子图,每个子图都有相同的x轴标签但是下面的代码我只能将标签传递到最后一个条形图。 My question is how can I pass the labels to both bar plots? 我的问题是如何将标签传递给两个条形图?

fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(18,15))

r1 = axes[0].bar(idx, data1, align='center')
axes[0].set_title('title1')

r2 = axes[1].bar(idx, data2, align='center')
axes[1].set_title('title2')

plt.xticks(idx, idx_labels, rotation=45)

plt.xticks as all other pyplot commands relate to the currently active axes. plt.xticks因为所有其他pyplot命令与当前活动的轴相关。 Having produced several axes at once via plt.subplots() , the last of them is the current axes, and thus the axes for which plt.xticks would set the ticks. 通过plt.subplots()一次生成多个轴,它们中的最后一个是当前轴,因此plt.xticks将设置刻度线的轴。

You may set the current axes using plt.sca(axes) : 您可以使用plt.sca(axes)设置当前轴:

import matplotlib.pyplot as plt

idx, data1, data2, idx_labels = [1,2,3], [3,4,2], [2,5,4], list("ABC")

fig, axes = plt.subplots(nrows=2, ncols=1)

r1 = axes[0].bar(idx, data1, align='center')
axes[0].set_title('title1')

plt.sca(axes[0])
plt.xticks(idx, idx_labels, rotation=45)

r2 = axes[1].bar(idx, data2, align='center')
axes[1].set_title('title2')

plt.sca(axes[1])
plt.xticks(idx, idx_labels, rotation=45)

plt.show()

However, when working with subplots, it is often easier to use the object-oriented API of matplotlib instead of the pyplot statemachine. 但是,在使用子图时,使用matplotlib的面向对象API而不是pyplot statemachine通常更容易。 In that case you'd use ax.set_xticks and ax.set_xticklabels , where ax is the axes for which you want to set some property. 在这种情况下,您将使用ax.set_xticksax.set_xticklabels ,其中ax是您要为其设置某些属性的轴。 This is more intuitive, since it is easily seen from the code which axes it being worked on. 这更直观,因为从代码中可以很容易地看出它正在处理哪些轴。

import matplotlib.pyplot as plt

idx, data1, data2, idx_labels = [1,2,3], [3,4,2], [2,5,4], list("ABC")

fig, axes = plt.subplots(nrows=2, ncols=1)

r1 = axes[0].bar(idx, data1, align='center')
axes[0].set_title('title1')

r2 = axes[1].bar(idx, data2, align='center')
axes[1].set_title('title2')

for ax in axes:
    ax.set_xticks(idx)
    ax.set_xticklabels(idx_labels, rotation=45)

plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM