繁体   English   中英

如何识别 matplotlib 中与 xaxis 或 yaxis 重叠的标签?

[英]How to identify labels overlapping with xaxis or yaxis in matplotlib?

如何识别与 xaxis 或 yaxis 重叠的标签并对其应用不同的设置?

这是代码:

import matplotlib.pyplot as plt
import numpy as np


labels = ["G1", "G2", "G3", "G4", "G5", "G6"]
men_means = [0.1, 34, 30, 35, 27, 100]

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x, men_means, width, label="Men")
ax.set_ylabel("Scores")
ax.set_title("Scores by group")
ax.set_xticks(x, labels)
ax.legend()

b1l = ax.bar_label(
    rects1,
    fontweight="bold",
    label_type="center",
    padding=5,
    rotation=90,
    bbox=dict(edgecolor="white", facecolor="cyan", alpha=0.5),
)
fig.tight_layout()
plt.show()

它产生以下图表:

条形图

并且仅对于那些与 xaxis 或 yaxis 重叠的值(在本例中为 xaxis),如何将label_type属性设置为edge

帮助图 2

我在另一个相关答案之后解决了这个问题!

import matplotlib.pyplot as plt
import numpy as np


labels = ["G1", "G2", "G3", "G4", "G5", "G6"]
men_means = [0.1, 34, 30, 35, 27, 100]

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x, men_means, width, label="Men")
ax.set_ylabel("Scores")
ax.set_title("Scores by group")
ax.set_xticks(x, labels)
ax.legend()

for rect in rects1:
    height = rect.get_height()
    hy = height/2
    if rect.xy[0] < 0:
        hy = height + 6
    ax.text(
        rect.get_x() + rect.get_width() / 2,
        hy,
        "%0.1f" % height,
        ha="center",
        va="center",
        fontweight="bold",
        rotation=90,
        bbox=dict(edgecolor="white", facecolor="cyan", alpha=0.5),
    )
fig.tight_layout()
plt.show()

在此处输入图像描述

暂无
暂无

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

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