0

My code draws a plot in Terminal in OSX El Capitan but not in PyCharm. Both Terminal and PyCharm interpreters are set to Anaconda Python 3.6.2 and have the necessary packages all installed.

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)

Also, I tried the solutions in Pycharm does not show plot and none of them really worked. For example, adding the following lines after plt.show(block=True) didn't solve the problem.

matplotlib.get_backend()
plt.interactive(False)
plt.figure()
Mona Jalal
  • 34,860
  • 64
  • 239
  • 408

1 Answers1

1

I recently encountered pretty much the same irritance, and had also tried the other solutions mentioned everywhere for matplotlib/etc. Seeing as Terminal (aka, regular python/ipython) runs these plots, I figured that there must be a workaround in PyCharm to run a pure console that would avoid the buggy overhead. Well, following the first answer's advice I found, you can simply access the Python Console that is in PyCharm, and it outputs plots normally.

Coolio2654
  • 1,589
  • 3
  • 21
  • 46
  • Should this be brought up to the attention of Python community? In that specific case, I ended up using my Windows 7 machine as I had to use PyCharm. – Mona Jalal Jan 18 '18 at 07:05
  • I am no expert on the matter yet, but it does seem a major bug that isn't being addressed in an adequately rigorous fashion, based on the different forums I've searched to find a solution. – Coolio2654 Jan 18 '18 at 07:12