在 matplotlib 中突出显示特定的 xlabel 值

问题描述 投票:0回答:1

这是我的数据框...

data = {'PEOI': [190, 105, 100, 150, 100, 170], 'PCHOI': [11, 6, 3, 16, 21, 8], 'STKS': [200, 250, 300, 350, 400, 450], 'CCHOI': [3, 8, 13, 18, 3, 23], 'CEOI': [154, 190, 578, 611, 736, 420]}
df = pd.DataFrame(data)
print(df)

我正在将此 DataFrame 绘制为...

plt.style.use("dark_background")
fig, axes = plt.subplots(2, 1, figsize=(17,15))
for (y1, y2), ax in zip([("CEOI", "PEOI"), ("CCHOI", "PCHOI")], axes):
      ax.bar(df["STKS"], df[y1], width=13, label=y1,color = 'blue')
      ax.bar(df["STKS"], df[y2], width=7, label=y2,color = 'yellow')
      ax.set_xlabel("STRIKES", fontsize=24, fontweight="bold", labelpad=10, color ='cyan')
      ax.set_ylabel("OPEN INTEREST", fontweight="bold", fontsize=24, labelpad=10)
      ax.set_xticks(df["STKS"].values)
      ax.tick_params(labelsize=20)
      ax.tick_params(axis="x", rotation=90)
      ax.legend(fontsize=18)
      if y1 == "CEOI":
        ax.set_title("OPEN INTEREST",fontsize=26,fontweight="bold", loc="left", color ='yellow')
      elif y1 == "CCHOI":
        ax.set_title("CHANGE IN OPEN INTEREST",fontsize=24,fontweight="bold", loc="left", color ='yellow')
      ax.grid(axis="y", linestyle=(0, (15, 8)), alpha=0.4) and ax.set_axisbelow(True)
      #ax.grid()
      for p in ax.patches:
            ax.annotate(format(p.get_height(), '.0f'),
                        (p.get_x() + p.get_width() / 2., p.get_height()),
                        ha='center', va='center',
                        xytext=(1.5, 4),
                        textcoords='offset points',
                        fontsize=16, fontweight="bold")
fig.tight_layout()
plt.show(block=True)

请如何使用所需的颜色和字体大小突出显示我的 xlabel 的任何所需值(比如说“STRIKES”中的“350”)。谢谢。

python dataframe matplotlib label
1个回答
0
投票

您可以在第一个循环之外定义标签的 mapper 及其格式,然后从

get_xticklabels
set_backgroundcolor
set_fontsize
:


d = {
    "350": {
        "bg_color": "red", "font_size": 25
    },
    # add more mappings if needed
}

# rest of the code
    for p in ax.patches:
        # rest of the code
        
        for t in ax.get_xticklabels():
            if (xtl:=t.get_text()) in d :
                t.set_backgroundcolor(d[xtl]["bg_color"])
                t.set_fontsize(d[xtl]["font_size"])

输出:

© www.soinside.com 2019 - 2024. All rights reserved.