简体   繁体   中英

AttributeError: 'str' object has no attribute 'add_artist' matplotlib

import numpy as np 
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage,AnnotationBbox

def get_flag(name):
    path = "flags/flags/{}.png".format(name)
    im = plt.imread(path)
    return im

def offset_image(name, ax, xy):
    img = get_flag(name)
    im = OffsetImage(img, zoom=0.72)
    im.image.axes = ax

    ab = AnnotationBbox(im, xy, frameon=False, xycoords='data', boxcoords="offset points", pad=0)

    ax.add_artist(ab)

ax = df.plot(kind='scatter',x='% of Ages 65+',y='COVID Fatality Rate', title='Correlation between % of Ages 65+ and COVID Fatality Rate')

for i, c in enumerate(df['Country']):
    offset_image(i, c, ax)

plt.show()

I'm annotating country flags instead of markers on a scatter plot. But AttributeError: 'str' object has no attribute 'add_artist' shows up. How do I fix this?

You have two errors related with your offset_image() .

Fisrtly, as ewong and Phani Rithvij point out in the comment, the order of parameter you define in the offset_image() and the order how you call it are not the same.

Secondly, xy parameter in AnnotationBbox needs to be a tuple or a list which represents a point in coordinates system. However, you only pass a value c .

Without changing how you define offset_image() , you only need to change how you call it like below:

for i, c in enumerate(df['Country']):
    offset_image(i, ax, (i, c))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM