绘制多组水平条形图时避免重叠,实现X轴分组布局的方法
问题
我需要绘制水平条形图,当前添加多组条形图(代码中被注释的行)时会出现重叠情况,希望将X轴拆分为多个,实现分组布局。以下是我目前的代码,补充说明:所有数值范围在-3到3之间。
import pandas as pd import matplotlib.pyplot as plt df=pd.DataFrame() df["yaxis"]=(9,10,22,24) df["A"]=(0.3498,-0.46,0.38,0.9) df["B"]=(0.85,-0.035,0.91,0) df["C"]=(0,0.058,0.88,0) len=df["yaxis"].size fig, ax = plt.subplots() ax.set_xlim(-3,3) ax.set_yticks(range(len)) ax.set_yticklabels(df.yaxis) ax.barh(range(len),df["A"].to_list(), color='r') #ax.barh(range(len),df["B"].to_list(), color='g') plt.axvline(x=0,color="black",linestyle='-') plt.show()
解决方案
要实现分组水平条形图,核心是给每组条形在y轴上设置偏移量,避免重叠。修改后的完整代码如下:
import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame() df["yaxis"] = (9, 10, 22, 24) df["A"] = (0.3498, -0.46, 0.38, 0.9) df["B"] = (0.85, -0.035, 0.91, 0) df["C"] = (0, 0.058, 0.88, 0) n_groups = len(df["yaxis"]) bar_width = 0.25 y_pos = range(n_groups) fig, ax = plt.subplots() ax.set_xlim(-3, 3) # 调整y轴刻度到分组中间位置,保证标签与分组对齐 ax.set_yticks([y + bar_width for y in y_pos]) ax.set_yticklabels(df.yaxis) # 每组条形设置不同y轴偏移,实现分组 ax.barh([y for y in y_pos], df["A"].to_list(), height=bar_width, color='r', label='A') ax.barh([y + bar_width for y in y_pos], df["B"].to_list(), height=bar_width, color='g', label='B') ax.barh([y + 2*bar_width for y in y_pos], df["C"].to_list(), height=bar_width, color='b', label='C') plt.axvline(x=0, color="black", linestyle='-') ax.legend() plt.show()
关键说明
bar_width:控制单个条形的高度(水平条形图中height参数对应条形高度),根据组数调整数值,确保分组间留有间隙。- y轴刻度偏移:将刻度位置调整到三个分组的中间,让标签与分组对齐更美观。
- 分组偏移逻辑:通过给每组条形的y轴位置加上倍数的
bar_width,让多组条形在y轴上错开,避免重叠实现分组布局。
内容的提问来源于stack exchange,提问作者Max Bushbeat
相关产品推荐
相关产品推荐

