2

How can I identify labels overlapping with xaxis or yaxis and apply different settings to them?

Here is the code:

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()

It produces the following chart:

bar chart

And only for those values that are overlapping with xaxis or yaxis (in this case it is the xaxis), how can I set the label_type property to edge?

help image 2

Abbas
  • 3,872
  • 6
  • 36
  • 63

1 Answers1

2

I solved the issue following another related answer!

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()

enter image description here

Abbas
  • 3,872
  • 6
  • 36
  • 63