toylas
toylas

Reputation: 437

pylab: different behavior in shell and script

I'm running into a weird problem with matplotlib. Here is my code:

f,a=subplots(3,1,sharex='col')
f.set_figheight(3.)
f.set_figwidth(3.)
## Make plots, set labels for a[0], a[1], a[2]
a[2].set_xlim(-4.40,6)

[plt.setp(i.get_xticklabels(),fontsize=9) for i in a]
[plt.setp(i.get_yticklabels(),fontsize=9) for i in a]
[i.set_yscale('log') for i in a]
[i.set_ylim(1e-4,1.) for i in a]

for i in a:
##The following part is problematic
   labels=[j.get_text() for j in i.get_yticklabels()]
## end problematic part
   print labels
   labels[1] = u''; i.set_yticklabels(labels)

f.subplots_adjust(hspace=0)
plt.show()

The problem is that part of for loop that gets yticklabels works fine if I run it in the shell after making the plot but it returns an empty list if I run it as part of the above script.

If I run the code within ipython using:

#Code run inside IPython shell
run -i 'myscript.py'

I get the following output:

['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']

This is not what I want. However, when I comment out the label modification in the script and run the following:

# Code run inside IPython shell
run -i 'myscript.py'
for i in a:
   labels=[j.get_text() for j in i.get_yticklabels()]
   print labels
   labels[1] = u''; i.set_yticklabels(labels)

I get the following output:

['', '$\\mathdefault{10^{-4}}$', '$\\mathdefault{10^{-3}}$', '$\\mathdefault{10^{-2}}$', '$\\mathdefault{10^{-1}}$', '$\\mathdefault{10^{0}}$', '']
['', '$\\mathdefault{10^{-4}}$', '$\\mathdefault{10^{-3}}$', '$\\mathdefault{10^{-2}}$', '$\\mathdefault{10^{-1}}$', '$\\mathdefault{10^{0}}$', '']
['', '$\\mathdefault{10^{-4}}$', '$\\mathdefault{10^{-3}}$', '$\\mathdefault{10^{-2}}$', '$\\mathdefault{10^{-1}}$', '$\\mathdefault{10^{0}}$', '']

which is the output I expect. I have no idea what might be happening here. Any help will be greatly appreciated. Also, is there a "pythonic" way of writing the for loop?

Thanks

Upvotes: 1

Views: 112

Answers (1)

NichtJens
NichtJens

Reputation: 1899

Actually, the for-loop is more "pythonic" than your misuse of list comprehension. See also here.

I think you should move all those into the for-loop... That way you have a single outer loop. In your code, you are doing the same loop five times.

As the Zen of Python says:

Readability counts.


For your actual question: You are running into this problem?

Your version of Matplotlib is too new (matplotlib.__version__ = 1.3.1 as per your comment). Hence, you cannot use the code in the accepted answer there, as per the first paragraph of that answer.

There, an answer that should work for newer version of matplotlib is given (but not accepted), too. The main trick is using axes.get_xticks().tolist() instead of axes.get_xticklabels() ...

Upvotes: 3

Related Questions