【问题标题】:Add axis to colorbar in python matplotlib在 python matplotlib 中将轴添加到颜色条
【发布时间】:2016-06-07 07:30:18
【问题描述】:

我正在尝试在 python 中生成如下图:

我已经完成了大部分工作,目前基于我想要的它看起来像这样:

我的代码是:

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()

有没有办法让当前的颜色条看起来像上面的那个?那么要使它更小并为其添加轴吗?

任何帮助将不胜感激。

【问题讨论】:

标签: python matplotlib colorbar


【解决方案1】:

这里的关键是cax kwarg 到colorbar。您需要创建一个插入轴,然后将该轴用于颜色条。

举个例子:

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()

【讨论】:

  • 很好的答案,谢谢。知道如何为对数图表获得相同的结果吗?使用 loglog 数字,我的结果看起来好多了,这就是我必须坚持使用它的原因。
  • 注意:如果要使用log10轴,可以将以下选项设置为hexbinxscale = 'log', yscale = 'log'
  • @tom 我实际上最终使用了 x 和 y 比例。不过感谢您的评论。
猜你喜欢
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 2021-01-07
  • 2020-05-31
相关资源
最近更新 更多