Jupyter Notebook中如何重新显示修改后的pandas已创建绘图
问题场景
假设我在Jupyter Notebook中创建一个柱状图,第一个单元格运行如下代码:
import pandas as pd import matplotlib.pyplot as plt speed = [0.1, 17.5, 40, 48, 52, 69, 88] lifespan = [2, 8, 70, 1.5, 25, 12, 28] index = ["snail", "pig", "elephant", "rabbit", "giraffe", "coyote", "horse"] df = pd.DataFrame({"speed": speed, "lifespan": lifespan}, index=index) plot = df.plot(kind='bar', stacked=True)
运行上述代码后会正常显示生成的堆叠柱状图:
之后在下一个单元格中对该图表进行修改,例如添加数据标签,代码如下:
for bar in plot.patches: height = bar.get_height() width = bar.get_width() x = bar.get_x() y = bar.get_y() label_text = height label_x = x + width / 2 label_y = y + height / 2 if label_text != 0: plot.text( label_x, label_y, int(label_text), ha="center", va="center", color="white", fontweight="bold", )
完成上述修改后,直接调用plt.show()没有任何输出,无法展示修改后的图表。
解决方法
出现这个问题的核心原因是:Jupyter Notebook默认在单个单元格执行完成后,会自动渲染该单元格内生成的matplotlib图表,执行结束后对应画布的输出流就会关闭,后续在其他单元格修改坐标轴对象时,plt.show()不会触发已经完成渲染的画布重新输出。
你只需要在修改图表的代码末尾,直接返回对应的Figure对象,Notebook就会自动重新渲染修改后的图表,不需要调用plt.show():
for bar in plot.patches: height = bar.get_height() width = bar.get_width() x = bar.get_x() y = bar.get_y() label_text = height label_x = x + width / 2 label_y = y + height / 2 if label_text != 0: plot.text( label_x, label_y, int(label_text), ha="center", va="center", color="white", fontweight="bold", ) # 直接返回画布对象触发渲染 plot.figure
如果需要更灵活的渲染控制,也可以导入IPython的display工具手动触发渲染:
from IPython.display import display # 所有图表修改操作完成后调用 display(plot.figure)
内容的提问来源于stack exchange,提问作者mrgou
相关产品推荐
相关产品推荐

