gpt4 book ai didi

python - 在另一个单元格中的 plot() 之后未呈现 AxesSubplot

转载 作者:行者123 更新时间:2023-12-04 08:48:37 27 4
gpt4 key购买 nike

我绘制了来自 pandas 的一些数据DataFrameJupyter notebook像这样的单元格:

    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类型为 <class 'matplotlib.axes._subplots.AxesSubplot'> .都好。
然后,在 下一个 单元格,我正在尝试绘制另一条线,重复使用 ax ,就像我对 ax.plot(xs, line2, color='yellow') 所做的一样:
ax.plot(w1_arr, errors, color='red')
print(type(ax))
然而,除了 ax 的类型之外,没有任何东西被渲染。 ,是一样的 <class 'matplotlib.axes._subplots.AxesSubplot'> .
问题:
  • 为什么什么都不渲染?是否因为在单个 Jupyter 单元中可以“重用”ax因为它会读取所有要绘制的命令,然后一次绘制所有内容?但是尝试“重用”是不行的ax在那个单细胞之外?
  • 为什么是ax的类型AxesSubplot而不仅仅是 Axes ?根据 DataFrame.plot() ,它应该返回 Axes,我已经明确设置了 backend='matplotlib'。
  • 最佳答案

    通过摆弄,我找到了一种使其工作的方法,但我也在研究它,这是一个有趣的行为广告,我也不完全理解它。
    我的感觉是,它与艺术家和渲染器如何在 Figure 中存储和持久化有关。或 Axes类和跨 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')
    如果你找到它背后的理由,请发布它,我和其他人可能会感兴趣。

    关于python - 在另一个单元格中的 plot() 之后未呈现 AxesSubplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64183654/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com