将轴添加到python matplotlib中的颜色栏 [英] Add axis to colorbar in python matplotlib

查看:63
本文介绍了将轴添加到python matplotlib中的颜色栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to produce a figure like the following in python:

我已完成大部分工作,目前基于我想要的内容:

I am done with most part of it and currently based on what I want it looks like this:

我的代码是:

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

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

Is there any way to make the current colorbar look like the one on top? So to make it smaller and add axis to it?

任何帮助将不胜感激.

推荐答案

此处的关键是 cax kwarg到 colorbar .您需要创建一个插入轴,然后将该轴用于颜色栏.

The key here is the cax kwarg to colorbar. You'll need to create an inset axes, and then use that axes for the 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,它不支持对数轴,因此我将这一部分省略了.)

If you wanted to get fancy and more precisely match things (Note: I'm using hexbin here, which doesn't support log axes, so I'm leaving that part out.)

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

这篇关于将轴添加到python matplotlib中的颜色栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆