Python 在另一个单元格中的plot()之后未呈现AxeSubplot
我将Python 在另一个单元格中的plot()之后未呈现AxeSubplot,python,pandas,dataframe,matplotlib,plot,Python,Pandas,Dataframe,Matplotlib,Plot,我将熊猫数据框中的一些数据绘制在Jupyter笔记本单元格中,如下所示: ax = data.plot('Weight', 'Height', kind='scatter', backend='matplotlib') print(type(ax)) ax.plot(xs, line1, color='red') print(type(ax)) ax.plot(xs, line2, color='yellow') print(type(ax))
熊猫
数据框
中的一些数据绘制在Jupyter
笔记本
单元格中,如下所示:
ax = data.plot('Weight', 'Height', kind='scatter', backend='matplotlib')
print(type(ax))
ax.plot(xs, line1, color='red')
print(type(ax))
ax.plot(xs, line2, color='yellow')
print(type(ax))
我看到ax
属于
类型。一切都好
然后,在下一个单元格中,我尝试绘制另一行,重复使用ax
,就像我对ax所做的那样。绘图(xs,line2,color='yellow')
:
但是,除了ax
的类型外,不会呈现任何内容,它与
的类型相同
问题:
ax
AxesSubplot
的类型不是简单的轴
?根据,它应该返回Axes,我已显式设置backend='matplotlib'通过摆弄,我找到了一种使它工作的方法,但我也在研究它。这是一种有趣的行为,我也不完全理解它 我的感觉是,它与艺术家和渲染器如何在
图形
或轴
类和jupyter单元中存储和持久化有关
以下代码段将起作用:
############################ CELL 1 ################################
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'a': np.random.randint(0,30,10), 'b': np.random.randint(0,30,10)})
fig, ax = plt.subplots()
df.plot('a', 'b', kind='scatter', backend='matplotlib', ax=ax)
ax.plot(np.arange(0,30,10), np.arange(0,30,10), color='red')
ax.plot(np.arange(0,30,10), np.arange(0,30,10)+5, color='yellow')
############################ CELL 2 ################################
ax.plot(np.arange(0,30,10), np.arange(0,30,10)+15, color='blue')
fig
此外,您观察到的行为还必须与jupyter的内联呈现相关。如果您使用将创建外部图形的qt
替换为%matplotlib qt
,您发布的代码将正常工作,如下所示:
############################ CELL 1 ################################
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib qt
df = pd.DataFrame({'a': np.random.randint(0,30,10), 'b': np.random.randint(0,30,10)})
ax = df.plot('a', 'b', kind='scatter', backend='matplotlib')
ax.plot(np.arange(0,30,10), np.arange(0,30,10), color='red')
ax.plot(np.arange(0,30,10), np.arange(0,30,10)+5, color='yellow')
############################ CELL 2 ################################
# minimize the figure that popped up and run the second cell
ax.plot(np.arange(0,30,10), np.arange(0,30,10)+15, color='blue')
如果你发现背后的理由,请张贴,我和其他人可能会感兴趣
############################ CELL 1 ################################
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib qt
df = pd.DataFrame({'a': np.random.randint(0,30,10), 'b': np.random.randint(0,30,10)})
ax = df.plot('a', 'b', kind='scatter', backend='matplotlib')
ax.plot(np.arange(0,30,10), np.arange(0,30,10), color='red')
ax.plot(np.arange(0,30,10), np.arange(0,30,10)+5, color='yellow')
############################ CELL 2 ################################
# minimize the figure that popped up and run the second cell
ax.plot(np.arange(0,30,10), np.arange(0,30,10)+15, color='blue')