【问题标题】:Why matplotlib does not show the scatter plot in a second cell of a Jupyter notebook?为什么 matplotlib 没有在 Jupyter 笔记本的第二个单元格中显示散点图?
【发布时间】:2021-04-16 10:49:07
【问题描述】:

我在 jupyter notebook 中绘制散点图,其中包含 2 个单元格

from matplotlib import pyplot as plt
import numpy as np

# Plot single point
# 1st, create a figure
fig = plt.figure()
# then create an 'ax' in this figure
ax = fig.add_subplot(111)
# plot red point at x=7, y=42
ax.scatter(x = [7], y = [42])

# Plot multiple points
# create a center
center = (7, 42)
# sample scaled normal distribution
datapoints = 10 * np.random.randn(50, 50)
# re-center data
datapoints[0, :] += center[0]
datapoints[1, :] += center[1]
# plot red point for every data-point
ax.scatter(x = datapoints[0, :], y = datapoints[1, :], color = "red")
plt.show()

第一个单元格返回

而第二个什么都不返回。能否请您详细说明一下这个问题?

更新:我试着把

ax
fig

在第二个单元格中。特别是,

# Plot multiple points
# create a center
center = (7, 42)
# sample scaled normal distribution
datapoints = 10 * np.random.randn(50, 50)
# re-center data
datapoints[0, :] += center[0]
datapoints[1, :] += center[1]
# plot red point for every data-point
ax
fig
ax.scatter(x = datapoints[0, :], y = datapoints[1, :], color = "red")
plt.show()

但运行第二个单元仍然没有返回任何内容。

【问题讨论】:

标签: python-3.x matplotlib jupyter-notebook scatter-plot


【解决方案1】:
# Plot multiple points
# create a center
center = (7, 42)
# sample scaled normal distribution
datapoints = 10 * np.random.randn(50, 50)
# re-center data
datapoints[0, :] += center[0]
datapoints[1, :] += center[1]

在此代码中,您向 X 和 y 数字添加了数字,这可能会使您的值超出 plt 窗口的大小。 尝试使用:

plt.ylim([0,100])
plt.xlim([0,15])

祝你好运!

编辑:我也尝试了您的代码,当我将两个单元格放入一个单元格时,它对我来说很好:

【讨论】:

  • 您的解决方案不起作用。它只显示一个空白图。
  • 但不是这样。 OP 说“什么都没有出现”,而不是“旧情节没有任何红点出现”。
  • 你是把所有代码都放在一个单元格中,还是放在两个单独的单元格中(就像我一样)?
  • 艾哈迈德,“你的代码对我有用”不是答案。你们两个不应该更详细地描述 Jupyter 笔记本的预设,以找出导致不同行为的差异。
【解决方案2】:

通常,您在要显示绘图的同一单元格中创建图形。 如果这两个图应该是独立的,只需在第二个单元格的开头添加以下行:

# creates figure and axis in one command without any additional settings
fig, ax = plt.subplots()

如果您希望这些散点位于同一轴上,则将 ax.scatter() 调用放入同一单元格中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-27
    • 2018-04-04
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多