[英]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
?
我在另一個相關答案之后解決了這個問題!
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.