【问题标题】:Plot doesn't show in PyCharm but shows in Terminal in OSX terminal绘图不在 PyCharm 中显示,但在 OSX 终端的终端中显示
【发布时间】:2018-03-17 17:29:37
【问题描述】:

我的代码在 OSX El Capitan 的终端中绘制了一个图,但在 PyCharm 中没有。终端和 PyCharm 解释器都设置为 Anaconda Python 3.6.2 并安装了所有必要的包。

def plot_data(samples, centroids, clusters=None):
    """
    Plot samples and color it according to cluster centroid.
    :param samples: samples that need to be plotted.
    :param centroids: cluster centroids.
    :param clusters: list of clusters corresponding to each sample.
    """

    colors = ['blue', 'green', 'gold']
    assert centroids is not None

    if clusters is not None:
        sub_samples = []
        for cluster_id in range(centroids[0].shape[0]):
            sub_samples.append(np.array([samples[i] for i in range(samples.shape[0]) if clusters[i] == cluster_id]))
    else:
        sub_samples = [samples]

    plt.figure(figsize=(7, 5))

    for clustered_samples in sub_samples:
        cluster_id = sub_samples.index(clustered_samples)
        #print(cluster_id)
        #print(clustered_samples[:,0])
        #print(clustered_samples[:,1])
        plt.plot(clustered_samples[:, 0], clustered_samples[:, 1], 'o', color=colors[cluster_id], alpha=0.75,
                 label='Data Points: Cluster %d' % cluster_id)

    plt.xlabel('x1', fontsize=14)
    plt.ylabel('x2', fontsize=14)
    plt.title('Plot of X Points', fontsize=16)
    plt.grid(True)

    # Drawing a history of centroid movement
    tempx, tempy = [], []
    for mycentroid in centroids:
        tempx.append(mycentroid[:, 0])
        tempy.append(mycentroid[:, 1])

    for cluster_id in range(len(tempx[0])):
        plt.plot(tempx, tempy, 'rx--', markersize=8)

    plt.legend(loc=4, framealpha=0.5)

    plt.show(block=True)

另外,我尝试了Pycharm does not show plot 中的解决方案,但没有一个真正奏效。例如,在plt.show(block=True) 之后添加以下行并不能解决问题。

matplotlib.get_backend()
plt.interactive(False)
plt.figure()

【问题讨论】:

    标签: python macos matplotlib pycharm anaconda


    【解决方案1】:

    我最近遇到了几乎相同的烦恼,并且还尝试了其他针对 matplotlib/etc 的解决方案。看到终端(又名普通 python/ipython)运行这些图,我认为 PyCharm 中必须有一种解决方法来运行一个纯控制台,以避免错误的开销。好吧,按照我找到的第一个answer's 建议,您可以简单地访问 PyCharm 中的 Python 控制台,它会正常输出绘图。

    【讨论】:

    • 是否应该引起 Python 社区的注意?在那种特定情况下,我最终使用了我的 Windows 7 机器,因为我不得不使用 PyCharm。
    • 我还不是这方面的专家,但根据我寻找解决方案的不同论坛,这似乎是一个没有以足够严格的方式解决的主要错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2018-07-08
    • 2012-08-27
    • 2020-11-04
    • 1970-01-01
    相关资源
    最近更新 更多