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:
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
?
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.