在Python的Matplotlib中为色条添加轴线

3

我正在尝试在Python中生成如下图所示的图形:

enter image description here

我已经完成了大部分工作,根据我的要求目前看起来是这样的:

enter image description here

我的代码是:

plt.scatter(x,y,marker="h",s=100,c=color)
plt.xscale('log')
plt.yscale('log')
plt.xlim([1, 10**3])
plt.ylim([1, 10**3])
plt.colorbar()
plt.show()

有没有办法让当前的色条看起来像顶部的那个?使其更小并添加轴?

非常感谢任何帮助。


请查看以下内容:http://matplotlib.org/examples/pylab_examples/axes_demo.html 和 http://matplotlib.org/1.3.1/examples/pylab_examples/colorbar_tick_labelling_demo.html - Phlya
1个回答

7
这里的关键在于 colorbar cax 参数。您需要创建一个插图轴,然后将该轴用于颜色条。
例如:
import numpy as np
import matplotlib.pyplot as plt

npoints = 1000
x, y = np.random.normal(10, 2, (2, npoints))

fig, ax = plt.subplots()
artist = ax.hexbin(x, y, gridsize=20, cmap='gray_r', edgecolor='white')

# Create the inset axes and use it for the colorbar.
cax = fig.add_axes([0.8, 0.15, 0.05, 0.3])
cbar = fig.colorbar(artist, cax=cax)

plt.show()

在这里输入图片描述

如果你想要更精确地匹配数据(注意:我在这里使用的是 hexbin,它不支持对数轴,所以我将省略该部分)。

import numpy as np
import matplotlib.pyplot as plt

npoints = 1000
x, y = np.random.normal(10, 2, (2, npoints))

fig, ax = plt.subplots()
artist = ax.hexbin(x, y, gridsize=20, cmap='gray_r', edgecolor='white')

cax = fig.add_axes([0.8, 0.15, 0.05, 0.3])
cbar = fig.colorbar(artist, cax=cax)

ax.spines['right'].set(visible=False)
ax.spines['top'].set(visible=False)
ax.tick_params(top=False, right=False)

cbar.set_ticks([5, 10, 15])
cbar.ax.set_title('Bin Counts', ha='left', x=0)
cbar.ax.tick_params(axis='y', color='white', left=True, right=True,
                    length=5, width=1.5)
cbar.outline.remove()

plt.show()

enter image description here


很棒的答案,谢谢。你有什么想法可以让我得到对数-对数图表的同样效果吗?使用对数-对数图表我的结果看起来好多了,这就是为什么我必须坚持使用它的原因。 - ahajib
2
注意:如果您想使用log10轴,可以将以下选项设置为“hexbin”:xscale ='log',yscale ='log' - tmdavison
@tom 我最终使用了x和y比例尺。不过还是感谢你的评论。 - ahajib

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