pylab:shell和脚本中的不同行为

时间:2016-06-23 20:01:43

标签: python matplotlib ipython

我遇到了matplotlib的奇怪问题。这是我的代码:

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()

问题是,如果我在制作绘图后在shell中运行它,那么得到yticklabels的for循环的一部分工作正常但是如果我将它作为上述脚本的一部分运行它会返回一个空列表。

如果我使用以下命令在ipython中运行代码:

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

我得到以下输出:

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

这不是我想要的。但是,当我在脚本中注释掉标签修改并运行以下内容时:

# 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)

我得到以下输出:

['', '$\\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}}$', '']

这是我期望的输出。我不知道这里会发生什么。任何帮助将不胜感激。还有," pythonic"编写for循环的方法?

由于

1 个答案:

答案 0 :(得分:3)

实际上,for循环比你滥用列表理解更“pythonic”。另请参阅here

我认为你应该将所有这些转移到for循环中......这样你就有了一个外循环。在你的代码中,你正在进行五次相同的循环。

正如Zen of Python所说:

  

可读性计数。

对于您的实际问题:您正在遇到this problem

您的Matplotlib版本太新了(根据您的评论matplotlib.__version__ = 1.3.1)。因此,根据该答案的第一段,您无法使用accepted answer中的代码。

在那里,一个应该适用于较新版本的matplotlib is given(但不被接受)的答案。主要技巧是使用axes.get_xticks().tolist()代替axes.get_xticklabels() ...