ale*_*sov 1 python matplotlib scatter-plot
我正在尝试使用手动限制设置来协调 Matplotlib 散点图中的点注释,但是我收到一条错误消息,或者我遇到了设计问题。
这是我的代码:
fig, ax = plt.subplots(figsize = (20,10)) #manual limit setting
plt.axis([-2,3,-2.5,5])
plt.scatter(x, y)
for i, txt in enumerate(n): #dot annotation
ax.annotate(txt, (x[i], y[i]))
Run Code Online (Sandbox Code Playgroud)
这是输出的屏幕截图(我得到的最终散点图是一个位于大白色矩形左角的小矩形:
我也试过这个:
fig, ax = plt.subplots(figsize = (20,10))
ax = plt.axis([-2,3,-2.5,5])
plt.scatter(x, y)
for i, txt in enumerate(n):
ax.annotate(txt, (x[i], y[i]))
Run Code Online (Sandbox Code Playgroud)
但是当然我收到了以下错误消息(即使图表正确显示,但每个对应点旁边没有标签)。
AttributeError: 'list' object has no attribute 'annotate'
Run Code Online (Sandbox Code Playgroud)
出现错误是因为我的循环试图遍历ax = plt.axis([-2,3,-2.5,5]),这确实没有意义。
有什么解决方案可以克服这个问题?
谢谢
出现此问题的原因是剪切时文本的特殊大小写。通常您可能希望显示轴外的文本。因此注释和文本有一个annotation_clip论点。但是,这会干扰bbox_inches="tight"保存注释时的选项,因为注释仍然被视为布局的一部分,因此图形仍然考虑轴外的注释。
两种解决方案:
设置annotation_clip 和 clip_on。即您可以明确地告诉注释在轴上进行剪辑:
ax.annotate(txt, (x[i], y[i]), annotation_clip=True, clip_on=True)
Run Code Online (Sandbox Code Playgroud)设置bbox_inches为None。使用 IPython 内联后端时,您可以告诉它不要通过以下方式扩展图形
%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
Run Code Online (Sandbox Code Playgroud)
在开始创建内容之前在一个单元格中。(这是在这个答案中看到的)