使用plotnine结合adjust_text时出现AttributeError问题求助
解决plotnine搭配adjust_text出现的AttributeError问题
错误原因
expand_points是adjustText库adjust_text()函数的顶层参数,但通过plotnine的geom_label(adjust_text=...)传递时,参数被错误转发给箭头补丁(FancyArrowPatch),导致不兼容错误。
解决方案
方案一:移除不兼容参数(快速修复)
如果不需要expand_points功能,直接从参数字典中移除该键即可正常运行:
adjust_text_dict = { 'arrowprops': { 'arrowstyle': '-', 'color': 'black' } } plot = (p9.ggplot(df, p9.aes("x", "y", label = 'name')) + p9.geom_point(shape = "D", color = "#666799", fill = "#4f82be", size = 4) + p9.ggtitle('Title') + p9.xlab("x") + p9.ylab("y") + p9.geom_smooth(method = 'lm', se = False) + p9.geom_label(adjust_text = adjust_text_dict) ) plot.draw()
方案二:手动调用adjust_text(灵活支持所有参数)
绕过plotnine的封装,直接使用adjustText原生函数调整标签,可完整支持expand_points等所有参数:
from adjustText import adjust_text import plotnine as p9 import matplotlib.pyplot as plt # 绘制基础图表,不设置adjust_text参数 plot = (p9.ggplot(df, p9.aes("x", "y", label = 'name')) + p9.geom_point(shape = "D", color = "#666799", fill = "#4f82be", size = 4) + p9.ggtitle('Title') + p9.xlab("x") + p9.ylab("y") + p9.geom_smooth(method = 'lm', se = False) + p9.geom_label() ) # 渲染图表并提取所有文本标签对象 fig = plot.draw() texts = [text for ax in fig.axes for text in ax.texts] # 调用adjust_text调整标签位置,支持所有原生参数 adjust_text(texts, expand_points=(2,2), arrowprops={ 'arrowstyle': '-', 'color': 'black' }) # 显示图表 plt.show()
内容的提问来源于stack exchange,提问作者user25670083
相关产品推荐
相关产品推荐

