Jupyter Notebook运行plotnine代码报错:'Figure'无set_layout_engine属性
问题:plotnine运行报错AttributeError: 'Figure' object has no attribute 'set_layout_engine'
在Jupyter Notebook中运行基于plotnine的ggplot代码,已安装plotnine库,但执行时触发以下错误。
运行代码
( ggplot(df_nousd) + aes(x="raised_currency_code") + geom_bar(color="blue", alpha = 0.2) + labs(title='Tipo de moneda, capital por startup', x ='Tipo de moneda', y = 'Cuantía') )
报错堆栈
AttributeError Traceback (most recent call last) \~\\anaconda3\\lib\\site-packages\\IPython\\core\\formatters.py in __call__(self, obj) 700 type_pprinters=self.type_printers, 701 deferred_pprinters=self.deferred_printers) \---> 702 printer.pretty(obj) 703 printer.flush() 704 return stream.getvalue() \~\\anaconda3\\lib\\site-packages\\IPython\\lib\\pretty.py in pretty(self, obj) 392 if cls is not object \\ 393 and callable(cls.__dict__.get('__repr__')): \---> 394 return _repr_pprint(obj, self, cycle) 395 396 return _default_pprint(obj, self, cycle) \~\\anaconda3\\lib\\site-packages\\IPython\\lib\\pretty.py in _repr_pprint(obj, p, cycle) 698 """A pprint that just redirects to the normal repr function.""" 699 # Find newlines and replace them with p.break_() \---> 700 output = repr(obj) 701 lines = output.splitlines() 702 with p.group(): \~\\anaconda3\\lib\\site-packages\\plotnine\\ggplot.py in __repr__(self) 112 Print/show the plot 113 """ \---> 114 figure = self.draw(show=True) 115 116 dpi = figure.get_dpi() \~\\anaconda3\\lib\\site-packages\\plotnine\\ggplot.py in draw(self, show) 239 # Artist object theming 240 self.theme.apply() \---> 241 figure.set_layout_engine(PlotnineLayoutEngine(self)) 242 243 return self.figure AttributeError: 'Figure' object has no attribute 'set_layout_engine'
解决方案
这个错误是因为你的matplotlib版本过低,set_layout_engine是matplotlib 3.6.0及以上版本才新增的方法,当前安装的matplotlib版本不支持该方法。解决步骤如下:
- 检查当前matplotlib版本:
import matplotlib print(matplotlib.__version__)
- 如果版本低于3.6.0,执行升级命令:
pip install --upgrade matplotlib
- 升级完成后,重启Jupyter Notebook,再重新运行你的plotnine代码即可。
内容的提问来源于stack exchange,提问作者Javier García Díez
相关产品推荐
相关产品推荐

