如何将Plotnine图表转换为Matplotlib形式以实现多图组合?
如何将Plotnine图表转换为Matplotlib形式以实现多图组合?
嘿,我来帮你搞定这个Plotnine转Matplotlib的问题~你遇到的显示空白问题,主要是因为对plotnine和Matplotlib的上下文交互理解有点偏差,咱们一步步来解决:
先梳理你的问题根源
你用P.draw()已经得到了Matplotlib的Figure对象,但之后调用plt.gca()会获取当前Pyplot的默认坐标轴,这和plotnine生成的独立Figure上下文冲突了,所以才会显示空白。其实plotnine的draw()方法已经直接返回了可用的Matplotlib Figure,咱们直接操作它就行。
修正后的基础转换代码
先看最简单的情况,把你的plotnine图正确转换成Matplotlib形式并显示:
首先是你的数据和plotnine绘图代码(我帮你保留了原内容):
import pandas as pd import plotnine as p9 from plotnine import * import matplotlib.pyplot as plt new_data = { 'date': pd.date_range('2022-01-01', periods=11, freq="ME"), 'parent_category': ['Electronics', 'Electronics', 'Fashion', 'Fashion', 'Home Goods', 'Electronics', 'Fashion','Electronics','Electronics','Electronics','Electronics'], 'child_category': ['Smartphones', 'Laptops', 'Shirts', 'Pants', 'Kitchenware','Laptops', 'Shirts', 'Smartphones','PS4','Oven','Vaccum cleaner'] } new_data = pd.DataFrame(new_data) # Plotnine绘图代码 P = (ggplot(new_data[new_data['parent_category'] == 'Electronics'], aes(x="date", y="child_category", group="child_category")) + geom_line(size=1, color="pink") + geom_point(size=3, color="grey") + theme_538() + theme(axis_text_x=element_text(angle=45, hjust=1), panel_grid_major=element_blank() ) )
接下来是正确的转换和显示代码:
# 将Plotnine图转换为Matplotlib Figure fig = P.draw() # 设置图的尺寸 fig.set_size_inches(8, 3, forward=True) # 直接显示这个Matplotlib图,不需要调用plt.gca() plt.show()
这样就能正常显示你的plotnine转换后的图了,和你原来的plotnine输出效果一致。
进阶:和其他Matplotlib图组合
如果你想把这个plotnine图和其他Matplotlib原生图放在同一个布局里,可以这样操作:
# 创建一个Matplotlib的Figure和子图布局(比如上下两个子图) fig, (ax_p9, ax_mat) = plt.subplots(2, 1, figsize=(8, 6)) # 将Plotnine的图绘制到指定的子轴ax_p9上 P._draw_using_figure(fig, [ax_p9]) # 在另一个子轴ax_mat上绘制Matplotlib原生图表 ax_mat.plot(pd.date_range('2022-01-01', periods=11, freq="ME"), [10,12,8,15,9,11,13,7,14,10,12]) ax_mat.set_title("Matplotlib原生折线图") ax_mat.tick_params(axis='x', rotation=45) # 调整子图间距 plt.tight_layout() plt.show()
这个方法的核心是用P._draw_using_figure()把plotnine的绘图内容直接渲染到你指定的Matplotlib坐标轴上,完美实现多图组合。
补充说明
你提到的参考文章里的转换逻辑,本质上也是利用plotnine和Matplotlib的底层交互,只是封装得更复杂一些。咱们上面的方法更直接,适合快速解决你的需求。
备注:内容来源于stack exchange,提问作者ViSa
相关产品推荐
相关产品推荐

