水平定向颜色条标记上的两个范围从颜色条“浮动”

时间:2014-04-14 06:40:59

标签: python matplotlib

使用this我可以在垂直方向的颜色条上绘制两个范围。因此,我想尝试对水平方向的颜色条做同样的事情。这有效,但部分原因。首先是代码:

import pylab as pl
import numpy as np
a = np.random.rand(10, 10)

pl.imshow(a)
cb = pl.colorbar(pad=0.1, orientation='horizontal')

l, b, w, h = cb.ax.get_position().bounds
cb.ax.set_aspect("auto")

ax2 =pl.twiny(ax=cb.ax)
cb.ax.set_position([l, b, w, h])
ax2.set_position([l, b, w, h])
cb.ax.set_ylim(0, 1)
ax2.set_ylim(-10, 10)
tight_layout()

然后输出:

enter image description here

这似乎没问题,但是顶部和底部的刻度都漂浮在颜色条的一定距离上,并且颜色条的高度非常小。通过增加高度,蜱变得更加远离色条。

有任何建议如何解决?

1 个答案:

答案 0 :(得分:2)

进行以下更改(请参阅代码中的注释):

import pylab as pl
import numpy as np
a = np.random.rand(10, 10)
pl.imshow(a)
cb = pl.colorbar(pad=0.1,  orientation='horizontal')

l, b, w, h = cb.ax.get_position().bounds
print l, b, w, h
cb.ax.set_aspect("auto")
#w = 0.05            # width of the colorbar (from the vertical example)
h = 0.05             # height of the colorbar
ax2 = pl.twiny(ax=cb.ax)
cb.ax.set_position([l, b, w, h])
ax2.set_position([l, b, w, h])
cb.ax.set_xlim(0, 1) # you are now dealing with an horizontal colorbar
                     # so you should define the x lim, not the y lim
ax2.set_xlim(-10, 10)
pl.show()

你生成这个图像: enter image description here