Dendrogram generated by scipy-cluster does not show - python

I am using scipy-cluster to generate a hierarchical clustering on some data. As a final step of the application, I call the dendrogram function to plot the clustering. I am running on Mac OS X Snow Leopard using the built-in Python 2.6.1 and this matplotlib package. The program runs fine, but at the end the Rocket Ship icon (as I understand, this is the launcher for GUI applications in python) shows up and vanishes immediately without doing anything. Nothing is shown. If I add a 'raw_input' after the call, it just bounces up and down in the dock forever. If I run a simple sample application for matplotlib from the terminal it runs fine. Does anyone have any experiences on this?

I had the same issue on Ubuntu 10.04.
In order to get graphics to display from ipython interactive console, start it with "-pylab" switch, which enables the interactive use of matplotlib:
ipython -pylab
To get your graphics to display during the execution of a standalone script, use matplotlib.pyplot.show call. Here's an example from hcluster homepage, the first and last line are the significant bits here:
from matplotlib.pyplot import show
from hcluster import pdist, linkage, dendrogram
import numpy
from numpy.random import rand
X = rand(10,100)
X[0:5,:] *= 2
Y = pdist(X)
Z = linkage(Y)
dendrogram(Z)
show()

Invoking ipython with "-pylab" switch didn't make a difference for me.
(System: Fedora 13)
Though not ideal, my solution was to explicitly write the resulting figure as a file.
For example:
...
dendrogram(Z)
pylab.savefig( "temp.png" )
Hope this helps anyone who is running into the same issue.
Amendment: Be careful about simply using copy-and-paste with the hcluster package's brief tutorial, notably in that if you call pylab.savefig() after several types of dendrogram drawing shown in the tutorial, i.e.
distMat = # whatever distance matrix you have
dendrogram( linkage( distMat ) )
pylab.savefig( "exampleDendrogram.png" )
dendrogram( linkage( distMat, method="complete" ) ) #instead of default "single"
pylab.savefig( "exampleDendrogram.png" )
Then exampleDendrogram.png will contain both the single-linkage dendrogram and the complete-linkage dendrogram in the same figure, and they will likely cross-cross and look like a mess.
If you're as stupid as me, you'll spend 30-180 minutes in confusion about how to properly use hcluster, when it's actually just a matter of resetting matplotlib between dendrogram calls:
distMat = # whatever distance matrix you have
dendrogram( linkage( distMat ) )
pylab.savefig( "exampleDendrogram1.png" )
pylab.cla()
dendrogram( linkage( distMat, method="complete" ) ) #instead of default "single"
pylab.savefig( "exampleDendrogram2.png" )
Now, the resulting dendrogram image files will look like what you expected them to look like.

I have been facing the same problem. You can use one of the below methods
Use plt.show() :
use plt.show() after dedogram, this will show the plot
using plt.show
Use %matplotlib inline intially in jupyter notebook. this will show the plot after execution.
Using matplotlib inline

Related

How to keep plotting window open in MNE with Python?

In MNE with Python, I would like to keep the interactive plotting window open once the calling def is executed completely.
However, this is not achievable via the following code:
def get_plot():
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)
raw.plot()
get_plot()
Such that, once the get_plot() is completed, the plot window is automatically closed.
Also, I am on Windows 10 with PyCharm 2020.1.3.
May I know how to handle this issue?
To get the interactive plot in PyCharm. The Show plots in tool window first need to be disabled.
Disable Settings | Tools | Python Scientific | Show plots in tool
window
Then, matplotlib.use('TkAgg') should allowed to create an interactive plot window.
MNE plot() is based on matplotlib. See the source file plot_raw. Based from the OP, matplotlib equip with block parameter you can pass to plt.show(). This allow the plot to be open even after the function is successfully invoke.
Apparently, mne group have include this parameter as well.
So, the above objective can be achieved simply by setting plot(block=True)
Then, the full code is
import mne
import matplotlib
matplotlib.use('TkAgg')
def get_plot():
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)
raw.plot(block=True)
get_plot()

Python ggplot: Is it possible to turn off the GUI displayed? and get a command-line ("non-interactive plotting"/"batch")

When plotting with Python ggplot, every single plot command causes a GUI pane to be displayed and suspend execution ("interactive plotting"). But I want to:
avoid/ turn off this GUI and save the plot object some where in runtime (I will be displaying it in some other C# forms control).
find a Python equivalent to dev.off() command in R language which turns off the GUI for plotting.
Example:
print ggplot(data, aes('Age', 'Weight')) + geom_point(colour='steelblue')
When I execute this, it opens up a new GUI (like below) displaying the plot.
You can do the following, which returns a matplotlib figure:
g = ggplot(...) + geom_xxx(...)
fig = g.draw()
ggplots __repr__() method (what is called by print(g) is basically self.draw() then use matplotlibs plt.show() to show the plot...
You can also use ggsave(g) to save the plot somewhere.
Since plotting is triggered by __repr__ method the obvious approach is to avoid situations when it is called. Since you want to use this plot in some other place there is no reason to call print or even executing statements which will be discarded like this:
ggplot(data, aes('Age', 'Weight')) + geom_point(colour='steelblue')
Instead you can simply assign it to the variable
p = ggplot(data, aes('Age', 'Weight')) + geom_point(colour='steelblue')
what is exactly the same thing one would do in R. Using graphic device to redirect output and discarding it doesn't really make sense.
If for some reason that's not enough you switch to non-interactive matplotlib backend:
import matplotlib
matplotlib.use('Agg')
from ggplot import *
ggplot(aes(x='date', y='beef'), data=meat)
<ggplot: (...)>

"Replot" a matplotlib inline plot in a IPython notebook

if I work on a matplotlib inline plot in an ipython notebook like this:
figure = plt.figure()
ax = figure.gca(projection="3d")
graph = np.empty([len(thetaYield),3])
for g, tY in zip(graph, thetaYield):
sample = HWtoPS(xiYield, rhoYield, tY)
g[...] = sample[:]
ax.plot(graph[:,0],graph[:,1], graph[:,2])
plt.show()
the plot is drawn inline in my notebook as it intended.
Now I want to add to add some data to this plot:
principalStress, vectors = eig(sigma)
ax.scatter(principalStress[0], principalStress[1], principalStress[2])
plt.show()
no error, but also no plot is drawn.
I expected to get an "updated" version of my plot with the additional data.
How can this be done?
A: This can be done at a cost of changed matplotlib Renderer
Currently, this cannot be done for the IPython "inline" graphs, however, if you opt to change a Renderer part of the matplotlib framework, to another one, the limitation of a singleton call of the .show() method does not hurt and you can ex post modify the object's content and it gets re-processed by the Renderer.
Simply:
add a directive ( IPython magic) %matplotlib qt
&
use additional matplotlib calls as you expect 'em to modify/update the figure object
( I love using this both during prototyping phases & for interactive 3D-viewing of complex data visualisations (which I heavily miss in notebook's "inline"s) )
BTW: do you have about any methodology, which would allow to store a matplotlib 3D-view plot, as a complete, state-full container, that can be sent to some other user for her/his "load" and UI-interactive review? Would be great to hear about any such working :o)

matplotlib.pyplot.draw() and matplotlib.pyplot.show() have no effect

In the past I was able to do simple animations with matplotlib with a for loop, but this hasn't worked for some time now.
The standard answer is that you have to turn interactive mode on and/or force a redraw with matplotlib.pyplot.draw(). Here is my minimal working example:
import numpy as np
import matplotlib
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as mplot
mplot.ion()
fig = mplot.figure(1)
ax = fig.add_subplot(111)
for ii in np.arange(0,10):
x = 200*np.random.rand(30)
ax.plot(x)
mplot.draw()
filename = ("img_%d.png" % ii)
mplot.savefig(filename)
When I run this in Interactive Python Editor, I get one figure at the very end with all the plots in it (this also happens with mplot.show())
When I run this in IPython 3.1 (with Python 3.3.5) from the command line, I get nothing at all.
The mplot.savefig(filename) line does seem to work, as the images are generated.
(It's possible this is a bug in the Qt4 backend.)
Try deleting the line matplotlib.use('Qt4Agg'). Works for me. Also works with matplotlib.use('TkAgg'). So it is a backend problem. There is another way to do animations.

ipython notebook pylab fig size running twice?

I am using iPython notebook wo do some visualization. Figures are inline (the profile defaults to interactive, as this supports a number of users who prefer interactive more frequently):
%pylab inline
Using the inline plot, I often set the fig size manually:
figsize(10,5)
I find that I need to run cells twice to realize a change in the fig size. For example, if I define cell [1] as figsize(10,5) and run it, the output is the correct size. If I then run cell [2] with `fig size(5,10)1 I get output that is of size (10,5). A second run of cell [2] draws correctly.
Any insight into why this is occurring? Is it due to the inline backend and I just need to live with it?
Thanks.
Definition: figsize(sizex, sizey)
Docstring:
Set the default figure size to be [sizex, sizey].
This is just an easy to remember, convenience wrapper that sets::
matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
This seem correct to me, if you run the following, whatever value of X, Y I always get the right plot
figsize(10,5)
plot(range(10))
if you run it after your plot, then you set the default for next plot... but without exact example, hard to say..

Categories

Resources