代码如下:
import itertools
import pandas as pd
import matplotlib.pyplot as plt
# reuse these colors
colors = itertools.cycle(["r", "b", "g"])
# some random data
df = pd.DataFrame({'x':[1,2,3,4,5],
'y':[2,4,5,2,4],
'area': [100, 200, 400, 500, 800],
'label': ['blah1','blah2','blah3','blah4','blah5']
})
# draw a scatter plot
def draw_scatter_plot(
x,
y,
marker_size,
marker_color: itertools.cycle,
labels
):
fig, ax = plt.subplots(figsize=(12, 8))
if marker_size:
i = 0
while i<len(x):
ax.scatter(x[i], y[i], color = next(marker_color), s = marker_size[i])
ax.annotate(
labels[i],
(x[i], y[i]), # adjust y[i] here
fontproperties=cur_font,
fontsize=14,
ha="center",
va="top",
)
i+=1
plt.show()
draw_scatter_plot(df.x.tolist(),
df.y.tolist(),
df.area.tolist(),
colors,
df.label.tolist())
如您所见,标签与圆的底部重叠。如何计算圆的底y值,以便始终定位标签,使其与圆不重叠?
答案 0 :(得分:0)
您可以按以下方式更改注释:
dir(javaRegexp)
使用此方法,必须根据x,y轴的缩放比例缩放yxtext坐标。
另外一条评论:由于您在while循环中使用它,因此您可能希望将其更改为:
[plt.annotate("{}, {}".format(x,y), xy=(x,y), xytext=(x-.1,y-.16)) for x, y in zip(x, y)]
答案 1 :(得分:0)
一种解决方案是使用this答案中所示的textcoords
。您可以关闭原始答案中的花式框。
ax.annotate(labels[i],(x[i], y[i]), xytext=(0, -15),
textcoords='offset points', fontsize=14,ha="center",va="top",)
答案 2 :(得分:0)