Matplotlib:如何调整等高线图中色条的线宽?

10
这里有一个最简示例,可以生成一个图表来说明我的问题:
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()

生成的图像如下所示:

gray_contours

我希望保持图中等高线的linewidths为0.75,但在colorbar中增加它们(以获得更好的可读性)。
如何在不改变图中的linewidths的情况下更改colorbar中的linewidths
我最初尝试使用CB.collections,但是colorbar没有collections。此外,使用参数linewidths=4.0调用colorbar无法工作(这是一个未知的参数)。 评论
当我输入这个问题时,我有了这个想法(橡皮鸭子调试):
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)

基本上,将linewidths的初始值设置为所需的colorbar级别,然后生成colorbar,之后使用collections在原始等高线上减小其线宽即可。
这样可以实现。
但是: 是否有一种直接控制colorbarlinewidths的方法?

如果将 linewidths=4.0 添加到 colorbar 中没有起作用,那么可能没有一种干净的方法(快速浏览代码似乎证实了这一点)。请参阅 colorbar.ColorBar.add_lines。它似乎是专门设计来明确地 跟随 等高线图中的线宽度的。 - tacaswell
2个回答

6

您只需找出如何访问这些行,让我们试试:

>>> 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>]

好的,请猜一下,我打赌第五项是分隔线列表。我们正在寻找一些.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.

the resultenter image description here


噢,试试使用get_children()而不是get_childern()看看是否有帮助。 - CT Zhu
那个打错字是我的问题,抱歉。它可以工作。我已经将它压缩成这个命令:CB.ax.get_children()[4].set_linewidths(5.0) - Schorsch
1
更改调色板的边缘线:CB.ax.get_children()[2].set_linewidths(5.0) - Marcos Alex
set_linewidths (in plural) does not work for me but this does: CB.lines[0].set_linewidth(5.0) - Václav Pavlík

1
使用 Axes.tick_params。 由于您使用 CB 作为颜色条的句柄,因此可以通过以下方式设置颜色条中的线宽:
CB.ax.tick_params(size = your_size, width = your_width)

size 是 colorbar 刻度线的长度。 width 是线宽。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接