matplotlib discrepancy with iPython notebook and python file - python

I have a strange problem with matplotlib that I can not seem to figure out. When using the ipython notebook with the pylab flag, ipython notebook --pylab inline I have a line of code that looks like this that is used to generate a colorbar with matplotlib:
im = ax.imshow(df, vmin=vmin, vmax=vmax)
The code works correctly and I get a nice colorbar. When I run this code as a python file I get an error, NameError: name 'ax' is not defined. I understand that the ipython notebook --pylab inline automatically imports a bunch of stuff into the notebook, but I cannot figure out what I need to import to fix the problem. print type(ax) gives:
<class 'matplotlib.axes.AxesSubplot'>
Can anyone point out why my code works in ipython but not a plain python file? Thanks in advance.

I had the same problem.
Per this entry:
How to abbreviate xtick labels years to 2 digits in a matplotlib plot
try defining 'ax' by adding (before the line causing the error):
ax = plt.gca()

I'm not quite sure what you've done, because aX isn't defined by default as part of pylab.
Normally, ax refers to an axis object. There are a few ways you can get one:
matplotlib.pyplot.gca() # gca = get current axis
matplotlib.pyplot.subplot(2,1,1) # For creating multiple plots in one figure
fig.get_axes()[x] # Where fig is a Figure object

Related

Python chart plot is empty

When I call:
model = doKMeans(user3, 4)
and then
ax.scatter(model.cluster_centers_[:,1], model.cluster_centers_[:,0],
s=169, c='r', marker='x', alpha=0.8, linewidths=2)
and then:
showandtell("Weekday Calls Centroids")
my chart appears empty. Any ideas why this is happening?
I believe the issue there is as simple as adding
plt.show()
to the end of your code.
Alternatively, another common mistake that might be causing that is that you if you are working on a jupyter notebook you might have forgot to add the command:
%matplotlib inline
when you import your matplotlib library
Hope that helps!

c++: Matplotlib pyplot show() giving SegFault

I want to create a log-log plot using pyplot, but have trouble when calling plt.show():
import matplotlib.pyplot as plt
xVec = [...]
yVec = [...]
plt.figure()
plt.loglog(xVec,yVec,'.',label='This is my test plot')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.show()
I am running this code from C++ via:
Py_Initialize();
Py_SimpleString(pythonCode.str().c_str());
Py_Exit(0);
where pythonCode is a stringstream containing the Python code above. The code runs if I don't include the plt.show() line, but of course no plot shows up.
The matplotlibrc config file shows that the backend is TkAgg, which shouldn't give problems as indicated here or here. I've tried adding plt.close() after the last line in the code above, but the error persists.
Perhaps the most surprising thing is this: I've also tried running the code in a separate Python script (with plt.show()), and the plot appears correctly! Does anyone have any idea about what's going on? Thanks in advance!
EDIT: I have also tried pylab instead of pyplot, with the same results. Do I need to compile the program with a certain python module to link the libraries properly?

Python 3.4 MatPlotLib PdfPages Value Error

I keep trying to follow the examples I see for PdfPages but keep getting the value error: No such figure: None.
plot1 = Chart Generating Function(argument1, argument2,...)
from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages('sample.pdf')
pp.savefig(plot1)
plt.close()
I've tried different variations of this (i.e. pdf.savefig()) but nothing seems to work.
What solved the problem for me was removing the plt.show() command at the end of my chart generating function.
I should have added more details, but somewhere in my code I had used "fig, ax = ..." when defining the figure. The "fig" part needed to be the argument in pdf.savefig(fig) in order for it to work.

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.

Keeping multiple figures open with matplotlib after script is executed

I have a question regarding windows/figures in matplotlib. I'm not sure if this is possible, but would like to know if it is.
Basically when I run my whole script, at the end a graph is plotted using matplotlib. In order to produce a new graph after running my script again I have to close that graph window.
Is there a way of keeping open the figure without closing it?
Let me give an example:
I would plot graph x by running my script.
I would then like to keep this graph on my screen, make a change to my script, plot the graph again so you may see the old graph and the new graph. Therefore n number of graphs may be visible.
Please note that I do NOT want to plot a new figure within my script. I simply would like to be able to see the graph, make a change and see the new graph WITHOUT having to save the graph.
EDIT:
This is the plotting secion of my code:
def plot_data(atb_mat_2, sd_index, sd_grad):#, rtsd):#, sd_index, sd_grad):
fig = plt.figure()
fig, (ax0, ax1, ax4, ax2, ax3) = plt.subplots(nrows=5, figsize=(15,10), num='Current Relative Method'+' ' + path)
ax0.plot(atb_mat_2)
ax0.set_title('Relative Track',fontsize=11)
ax0.set_ylim([-10,10])
if len(sd_index)!=0:
if len(sd_index)>1:
for i in range(1, len(sd_index)):
if sd_grad[i]==1:
ax0.axvspan(sd_index[i-1],sd_index[i], edgecolor='r', lw=None, alpha=0.1)
ax1.plot(rtsd)
ax1.set_title('RT Standard Deviation',fontsize=11)
ax1.set_ylim([0,250])
ax4.plot(abs_track_data)
ax4.set_title('Absolute Track',fontsize=11)
ax4.set_ylim([3000,5000])
ax2.plot(splitpo)
ax2.set_title('Track Split',fontsize=11)
ax2.set_ylim([0,20])
ax3.plot(ts)
ax3.set_title('TS Standard Deviation',fontsize=11)
ax3.set_ylim([0,100])
fig.tight_layout()
plt.show()
Thanks alot of any advice and sorry if this answer is obvious as I'm fairly new.
You can do it using ipython.
Write your script and save it as (for example) test.py. The script should create a figure, do the plotting and show the plot:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
x = np.linspace(-1, 1, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()
Start the ipython console using:
ipython --pylab=qt
Or whatever backend you want to use.
In the ipython shell type:
%run /path/to/the/test.py
This will create a figure, and show the plot.
After that change your script. For example change the 5th line to:
x = np.linspace(-0, 2, 100)
Repeat the %run command in the ipython shell:
%run /path/to/the/test.py
Another figure will pop up with the new plot. Old figure will be also visible (this won't remove it or replace it).

Categories

Resources