python - 在python matplotlib中将轴添加到colorbar

标签 python matplotlib colorbar

我正在尝试在 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()

有什么方法可以使当前的颜色条看起来像上面的颜色条吗?因此,要使其更小并为其添加轴?

如有任何帮助,我们将不胜感激。

最佳答案

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

举个例子:

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

enter image description here

如果你想要花哨和更精确地匹配东西(注意:我在这里使用 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

关于python - 在python matplotlib中将轴添加到colorbar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35611806/

相关文章:

matlab - Matlab 中的颜色条重复范围标签

python - 迭代平方中完成的乘法次数

python - 可以使这段代码更 Pythonic 吗?循环

python - 完全删除图例 handle 和标签

python - 使用 pandas 在数据框上进行多图绘制

python - Matplotlib:subplot2grid 中图外的颜色条

python - 如何避免 NumPy 中的嵌套 for 循环?

python - 使用 2D 矩阵作为 numpy 中 3D 矩阵的索引?

python - 如何增加 Pandas 数据框图的填充?

python - Matplotlib 归一化颜色条 (Python)