Plot不在PyCharm中显示,但在OSX终端的终端中显示

时间:2017-10-06 00:48:49

标签: python macos matplotlib pycharm anaconda

我的代码在OSX El Capitan的终端中绘制了一个图,但在PyCharm中没有。 Terminal和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()

1 个答案:

答案 0 :(得分:1)

我最近遇到了同样的烦恼,并且还尝试过为matplotlib / etc提到的其他解决方案。看到终端(也就是普通的python / ipython)运行这些图,我认为在PyCharm中必须有一个解决方法来运行一个可以避免错误开销的纯控制台。好吧,按照我发现的第一个answer's建议,您只需访问PyCharm中的Python控制台,它就会正常输出图表。