这是一个生成图表的最小例子,它说明了我的问题:
import matplotlib.pylab as plt
import matplotlib.mpl as mpl
import numpy as np
import random
data = [[random.random() for i in range(10)] for j in range(10)]
[XT, YT] = np.meshgrid(np.arange(1,10+1,1), np.arange(1,10+1,1))
cmap = mpl.cm.gray
fig, ax = plt.subplots()
CS = ax.contour(XT, YT, data,levels=np.arange(0,1+0.1,0.1),\
cmap=cmap,linewidths=0.75)
CB = plt.colorbar(CS, ticks=np.arange(0,1+0.1,0.1))
plt.show()
Run Code Online (Sandbox Code Playgroud)
结果图看起来像这样:
我想保留图linewidths
中的轮廓线,0.75
但增加它们colorbar
(为了更好的可读性).
如何linewidths
在colorbar
不更改图中的情况下更改?
我最初尝试过CB.collections
,但colorbar
没有collections
.此外,colorbar
使用参数调用linewidths=4.0
不起作用(它是一个未知参数).
评论
在输入这个问题时,我有了这个想法(橡皮鸭调试):
CS = ax.contour(XT, YT, data,levels=np.arange(0,1+0.1,0.1),\
cmap=cmap,linewidths=4.0)
CB = plt.colorbar(CS, ticks=np.arange(0,1+0.1,0.1))
plt.setp(CS.collections , linewidth=0.75)
Run Code Online (Sandbox Code Playgroud)
基本上,将初始设置为linewidths
所需的级别colorbar
,然后在原始轮廓线上生成colorbar
和之后使用collections
以减小其线宽.
这有效.
但:有没有办法直接控制linewidths
的colorbar
?
您只需要了解如何访问这些线路,让我们尝试一下:
>>> CB.ax.get_children()
[<matplotlib.axis.XAxis object at 0x026A74B0>, <matplotlib.axis.YAxis object at 0x026AF270>, <matplotlib.lines.Line2D object at 0x026AF190>, <matplotlib.patches.Polygon object at 0x027387F0>, <matplotlib.collections.LineCollection object at 0x02748BD0>, <matplotlib.text.Text object at 0x026C0D10>, <matplotlib.patches.Rectangle object at 0x026C0D50>, <matplotlib.spines.Spine object at 0x026A7410>, <matplotlib.spines.Spine object at 0x026A7290>, <matplotlib.spines.Spine object at 0x026A7350>, <matplotlib.spines.Spine object at 0x026A71B0>]
Run Code Online (Sandbox Code Playgroud)
好吧,猜猜看,我打赌第五项是分隔线列表。我们正在寻找一些.line
物体,有两个。第一个(第三项)实际上是整个颜色条的边缘(如果我没记错的话)。所以我会去寻找下一个.line
对象。
现在我们尝试从以下几个方面来修改它:
>>> len(lines1[4].get_linewidths())
11 #how many item are there? 11 lines
>>> lines1[4].set_color(['r']*11) #set them all to red, in this example we actually want to have the color stay the same, this is just for a demonstration.
>>> lines1[4].set_linewidths([2]*11) #set them all to have linewidth of 2.
Run Code Online (Sandbox Code Playgroud)
结果