Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

python - How to conciliate dots annotation in Matplotlib scatter plot with manual limit setting?

I'm trying to conciliate dots annotation in a Matplotlib scatter plot with a manual limit setting, but I either got an error message or I get a design problem.

Here is my code :

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]))

Here is a screen cap of the output (I got the final scatter plot as a small rectangle located in the left corner of a big white rectangle :

Output

I tried this also :

 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]))

But of course I got the following error message (even though the chart correctly displays, but without the labels next to each corresponding dot).

AttributeError: 'list' object has no attribute 'annotate'

The error arises because my loop tries to iterate through ax = plt.axis([-2,3,-2.5,5]), which doesn't make sense indeed.

Any solution to overcome this issue ?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem occurs because of the special casing of texts when it comes to clipping. Usually you might want text outside the axes to be shown. Therefore annotations and text have a annotation_clip argument. However, this interferes with the bbox_inches="tight" option when saving annotations, because the annotations is then still considered part of the layout and hence the figure takes annotations outside the axes still into account.

Two solutions:

  1. Set annotation_clip and clip_on. I.e. You may explicitely tell the annotation to clip at the axes:

    ax.annotate(txt, (x[i], y[i]), annotation_clip=True, clip_on=True)
    
  2. Set bbox_inches to None. When using the IPython inline backend you can tell it not to expand the figure via

    %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
    

    in a cell before starting to create your content. (This is seen in this answer)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...