作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想采用类似这样的代码来进行散点图注释...
import matplotlib; matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
labels = ["Abra", "Kadabra", "Alazkazam", "Mew"]
x_values = [0.3, 0.6, 0.2, 0.4]
y_values = [0.2, 0.2, 0.4, 0.9]
fig = plt.figure(figsize=(5, 5))
plt.axis('off')
renderer = fig.canvas.get_renderer()
for i, label in enumerate(labels):
plt.scatter(x_values[i], y_values[i])
text_object = plt.annotate(label, xy=(x_values[i], y_values[i]))
plt.savefig("horizontally_centered_text_annotations.png")
我尝试获取文本框周围的窗口范围,获取 x 坐标和宽度,然后为每个注释移动,如下所示:
for i, label in enumerate(labels):
plt.scatter(x_values[i], y_values[i])
text_object = plt.annotate(label, xy=(x_values[i], y_values[i]))
text_window_extent = text_object.get_window_extent(renderer)
new_x_position = x_values[i] - text_window_extent.width / 2
text_object.set_position((new_x_position, y_values[i]))
print "x_value: {}, window_extent_width: {}, new_x_position: {}".format(x_values[i], text_window_extent.width, new_x_position)
但是正如您从打印语句中看到的,宽度太大:
x_value: 0.3, window_extent_width: 31.5, new_x_position: -15.45
x_value: 0.6, window_extent_width: 56.0, new_x_position: -27.4
x_value: 0.2, window_extent_width: 72.875, new_x_position: -36.2375
x_value: 0.4, window_extent_width: 30.75, new_x_position: -14.975
不确定这是否与坐标系有关...
最佳答案
在annotate
调用中使用horizontalalignment
(可以缩写为ha
)选项:
text_object = plt.annotate(label, xy=(x_values[i], y_values[i]), ha='center')
关于matplotlib - 如何将注释水平居中在一个点上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38173517/
我是一名优秀的程序员,十分优秀!