簡體   English   中英

在python matplotlib中將軸添加到colorbar

[英]Add axis to colorbar in python matplotlib

我試圖在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()

有沒有辦法讓當前的colorbar看起來像頂部的那個? 那么要縮小它並添加軸嗎?

任何幫助將非常感激。

這里的關鍵是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()

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM