我在使用 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循环?
谢谢
最佳答案
实际上,for 循环比您对列表理解的滥用更“Pythonic”。另请参阅here .
我认为你应该将所有这些移到 for 循环中......这样你就有了一个外循环。在您的代码中,您将执行相同的循环五次。
作为Zen of Python说:
<小时/>Readability counts.
对于您的实际问题:您遇到 this problem ?
您的 Matplotlib 版本太新(根据您的评论,matplotlib.__version__ = 1.3.1
)。因此,您不能使用 accepted answer 中的代码在那里,按照该答案的第一段。
这里有一个适用于较新版本的 matplotlib is given 的答案(但不被接受)。主要技巧是使用 axes.get_xticks().tolist()
而不是 axes.get_xticklabels()
...
关于python - pylab : different behavior in shell and script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38000793/