使用多个条形图控制子图中的刻度标签 [关闭]

Control tick labels in subplots with multiple bar charts [closed]

提问人:Philipp 提问时间:11/17/2023 最后编辑:Philipp 更新时间:11/17/2023 访问量:37

问:


这个问题是由错别字或无法再现的问题引起的。虽然类似的问题可能在这里是主题,但这个问题的解决方式不太可能帮助未来的读者。

昨天关闭。

我想完全控制子图中的刻度标签,但我遇到了一个问题,即对单个图有效的方法不会转移到多个图中。

举一个具体的例子,我喜欢将 https://www.geeksforgeeks.org/plotting-multiple-bar-charts-using-matplotlib-in-python/ 的第一个例子推广到子图,例如,只是并排绘制相同的两次。

非常感谢您的帮助!

更多细节:我遇到的问题是

plts[0].xticks(X_axis, X)

创建错误消息 AttributeError: 'AxesSubplot' object has no attribute 'xticks'。我在互联网上找到的假定解决方案是将前面的表达式替换为

plts[0].set_xticks(X_axis, X) 

这不会产生任何警告,但不会产生预期的效果。刻度仍然标有“1”、“2”、“3”和“4”,而不是“A组”、“B组”、“C组”和“D组”。关于 xlabel、ylabel 和 title 的所有其他内容都可以使用。蜱虫有什么问题?如何在子图中完全控制它们?老实说,我不明白为什么这如此复杂。

非常感谢您的帮助!

更新:这是我的完整代码,以确保更好的可重复性:

import numpy as np  
import matplotlib.pyplot as plt  

def main():

X = ['Group A','Group B','Group C','Group D'] 
Ygirls = [10,20,20,40] 
Zboys = [20,30,25,30] 

fig, plts = plt.subplots(1,2 , figsize = (10,5), sharex = False, sharey = False)

X_axis = np.arange(len(X)) 

plts[0].bar(X_axis - 0.2, Ygirls, 0.4, label = 'Girls') 
plts[0].bar(X_axis + 0.2, Zboys, 0.4, label = 'Boys') 

plts[0].set_xticks(X_axis, X) 
plts[0].set_xlabel("Groups") 
plts[0].set_ylabel("Number of Students") 
plts[0].set_title("Number of Students in each group") 
plts[0].legend() 

plts[1].bar(X_axis - 0.2, Ygirls, 0.4, label = 'Girls') 
plts[1].bar(X_axis + 0.2, Zboys, 0.4, label = 'Boys') 

plts[1].set_xticks(X_axis, X) 
plts[1].set_xlabel("Groups") 
plts[1].set_ylabel("Number of Students") 
plts[1].set_title("Number of Students in each group") 
plts[1].legend() 

fig.savefig("test.pdf", bbox_inches='tight')

if __name__ == '__main__':
main()
matplotlib 条形图 子图 xticks

评论


答: 暂无答案