[英]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.我在散布 plot 上注释国旗而不是标记。 But AttributeError: 'str' object has no attribute 'add_artist' shows up.
但是 AttributeError: 'str' object has no attribute 'add_artist' 出现。 How do I fix this?
我该如何解决?
You have two errors related with your offset_image()
.您有两个与您的
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.首先,正如 ewong 和 Phani Rithvij 在评论中指出的那样,您在
offset_image()
中定义的参数顺序和您调用它的顺序是不一样的。
Secondly, xy parameter in AnnotationBbox needs to be a tuple or a list which represents a point in coordinates system.其次, AnnotationBbox中的xy参数需要是一个元组或一个列表,表示坐标系中的一个点。 However, you only pass a value
c
.但是,您只传递一个值
c
。
Without changing how you define offset_image()
, you only need to change how you call it like below:在不更改定义
offset_image()
的方式的情况下,您只需更改调用方式,如下所示:
for i, c in enumerate(df['Country']):
offset_image(i, ax, (i, c))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.