Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

python 3.x - Why matplotlib does not show the scatter plot in a second cell of a Jupyter notebook?

I'm drawing scatter plot in jupyter notebook which contains 2 cells

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])

and

# 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()

The first cell returns

enter image description here

whereas the second one returns nothing. Could you please elaborate on this problem?

Update: I tried to put

ax
fig

in the second cell. In particular,

# 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()

But running second cell still returns nothing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
# 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]

in this code you added numbers to the X and y numbers which may made your values out of the size of your plt window. try using:

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

Good luck!

Edit : I also tried your code and it works fine with me when i put both cells into one cell :

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...