下面给出的代码在正常的python环境中完美运行,但在jupyter笔记本环境中没有显示任何输出

问题描述 投票:0回答:1

代码:

%matplotlib widget
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

# Generate random data for demonstration
np.random.seed(0)
x = np.random.randn(100)  # Example dataset

# Define the update function for the animation
def update(curr):
    # Check if animation is at the last frame, and if so, stop the animation
    if curr == len(x):
        a.event_source.stop()
        
    # Clear the current axes
    plt.cla()
    
    # Set bins for histogram
    bins = np.arange(-4, 4, 0.5)
    
    # Plot histogram
    plt.hist(x[:curr], bins=bins)
    
    # Set the axes limits
    plt.axis([-4, 4, 0, 30])
    
    # Add labels
    plt.gca().set_title('Sampling the Normal Distribution')
    plt.gca().set_ylabel('Frequency')
    plt.gca().set_xlabel('Value')
    plt.annotate('n = {}'.format(curr), [3, 27])

# Quick to start
fig = plt.figure()  # Create figure
a = animation.FuncAnimation(fig, update, frames=len(x)+1, interval=100, cache_frame_data=False)

# Display the animation
plt.show()

enter image description here

我试图动画化 matplotlib 库的功能,但它只是运行,但在 jupyter 笔记本中没有显示任何输出? 请帮忙解决这个问题

matplotlib animation jupyter-notebook data-science visualization
1个回答
0
投票

根据您提供的内容,您的问题无法重现。
前往此处并点击“

launch binder
”。当笔记本打开时,粘贴以下代码:

%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

# Generate random data for demonstration
np.random.seed(0)
x = np.random.randn(100)  # Example dataset

# Define the update function for the animation
def update(curr):
    # Check if animation is at the last frame, and if so, stop the animation
    if curr == len(x):
        a.event_source.stop()
        
    # Clear the current axes
    plt.cla()
    
    # Set bins for histogram
    bins = np.arange(-4, 4, 0.5)
    
    # Plot histogram
    plt.hist(x[:curr], bins=bins)
    
    # Set the axes limits
    plt.axis([-4, 4, 0, 30])
    
    # Add labels
    plt.gca().set_title('Sampling the Normal Distribution')
    plt.gca().set_ylabel('Frequency')
    plt.gca().set_xlabel('Value')
    plt.annotate('n = {}'.format(curr), [3, 27])

# Quick to start
fig = plt.figure()  # Create figure
a = animation.FuncAnimation(fig, update, frames=len(x)+1, interval=100, cache_frame_data=False)

# Display the animation
plt.show()

我更改了第一行,因为我正在使用 Jupyter Notebook 的经典界面。

如果我一直在使用 JupyterLab 或 Jupyter Notebook 7+,那么我会安装 ipympl 并在代码顶部使用

%matplotlib ipympl
。请参阅此处。 (
%matplotlib widget
根据“基本示例”那里应该具有相同的效果。)

顺便说一句,我想有一次我收到了关于您使用

plt.show()
的警告。在现代 Jupyter 中没有必要,因为它会检测到 Matplotlib 绘图对象已创建、保持活动状态并显示它。所以你可以这样结束你的代码:

...

# Quick to start
fig = plt.figure()  # Create figure
a = animation.FuncAnimation(fig, update, frames=len(x)+1, interval=100, cache_frame_data=False)

...
代表前面的部分。

© www.soinside.com 2019 - 2024. All rights reserved.