当我在matplotlib中调用plt.show()时,图未显示

时间:2020-08-07 08:15:10

标签: python matplotlib seaborn

我目前正在学习python,我在一本书中看到了这段代码,但是对我来说不起作用。这是关于模具旋转的动态可视化:

from matplotlib import animation
import matplotlib.pyplot as plt
import random
import seaborn as sns


def update(frame_number, rolls, faces, frequencies):
    for i in range(rolls):
        frequencies[random.randrange(1, 7) - 1] += 1
    plt.cla()
    axes = sns.barplot(faces, frequencies, palette='bright')
    axes.set_title(f'Die Frequencies for {sum(frequencies):,} Rolls')
    axes.set(xlabel='Die Value', ylabel='Frequency')
    axes.set_ylim(top=max(frequencies) * 1.10)
    for bar, frequency in zip(axes.patches, frequencies):
        text_x = bar.get_x() + bar.get_width() / 2.0
        text_y = bar.get_height()
        text = f'{frequency:,}\n{frequency / sum(frequencies):.3%}'
        axes.text(text_x, text_y, text, ha='center', va='bottom')


number_of_frames = 10000  
rolls_per_frame = 600
sns.set_style('whitegrid')
figure = plt.figure('Rolling a Six-Sided Die')
values = list(range(1, 7))
frequencies = [0] * 6

die_animation = animation.FuncAnimation(figure, update, repeat=False, frames=number_of_frames, interval=33,
                                        fargs=(rolls_per_frame, values, frequencies))
plt.show()

运行脚本后,没有任何反应。 请注意,matplotlib和seaborn在我的系统中正常工作。我事先将它们用于静态可视化。

enter image description here

此代码没有问题:

import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as sns

rolls = [random.randrange(1, 7) for i in range(600)]

values, frequencies = np.unique(rolls, return_counts=True)

title = f'Rolling a six-sided die {len(rolls):,} Times'
sns.set_style('whitegrid')
axes = sns.barplot(x=values, y=frequencies, palette='bright')
axes.set_title(title)
axes.set(xlabel='Die value', ylabel='Frequency')

axes.set_ylim(top=max(frequencies) * 1.10)

for bar, frequency in zip(axes.patches, frequencies):
    text_x = bar.get_x() + bar.get_width() / 2.0
    text_y = bar.get_height()
    text = f'{frequency:,}\n{frequency / len(rolls):.3%}'
    axes.text(text_x, text_y, text, fontsize=11, ha='center', va='bottom')

plt.show()

enter image description here

我不知道为什么第一个代码中没有显示图。

2 个答案:

答案 0 :(得分:1)

仅从matplotlib导入动画,您的代码运行得很好

from matplotlib import animation

enter image description here

答案 1 :(得分:0)

似乎问题出在pycharm专业版。它在专业版中不起作用,但在社区版中起作用。 感谢Adhun Thalekkara注意到这一点。 我使用cmd来运行代码,它对我来说正常工作。