Colorbar ticks格式化不起作用

时间:2015-12-26 17:19:55

标签: python matplotlib

我有以下代码生成带有颜色条的散点图:

#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
from matplotlib.ticker import *
import matplotlib.ticker as ticker
import matplotlib as mpl
import matplotlib.gridspec as gridspec
from list2nparr import list2nparr

# this part changes the fonts for latex handling
plt.rcParams['text.latex.preamble']=[r"\usepackage{lmodern}"]
plt.rcParams['text.usetex'] = True
plt.rcParams['font.family'] = 'lmodern'
plt.rcParams['font.size'] = 16
#==================================================================
fig,ax1 = plt.subplots()
data = list2nparr('radiant.txt')
lm  = data[:,14]
bet = data[:,15]
b   = data[:,18]
#
cm = plt.cm.get_cmap('jet')
sc2 = ax1.scatter(lm, bet, c=b, s=10, cmap=cm, edgecolor='none',rasterized=True)
# ==========================COLORBAR SPECS=========================
cb3 = fig.colorbar(sc2,ax = ax1, aspect=10)
cb3.ax.tick_params(labelsize=16)
cb3.set_label(r'$\beta = F_R/F_G$',size=18,labelpad=20)
cb3.formatter.set_powerlimits((0, 0))
cb3.ax.yaxis.set_major_locator(MaxNLocator(5,prune='upper')) # WHY DOES THIS LINE NOT WORK?
cb3.update_ticks()

# =======================SCATTER PLOT SPECS========================
ax1.set_ylabel('$b$, (deg)',fontsize=18,labelpad=0.5)
ax1.set_xlabel("$\lambda-\lambda_{\odot}$, (deg)",fontsize=18)
plt.savefig('test.eps', format='eps')

在某些时候,我正在尝试格式化颜色条的刻度,在删除最上面的标签时仅请求五个刻度。这在第30行中说明,其中显示:cb3.ax.yaxis.set_major_locator(MaxNLocator(5,prune='upper'))

然而,这条线似乎对情节没有任何影响?
任何想法可能是什么原因?

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

修改

创建颜色栏时使用定位器:

cb3 = fig.colorbar(sc2,ax = ax1, aspect=10, ticks=MaxNLocator(5))

并删除此行:

cb3.ax.yaxis.set_major_locator(MaxNLocator(5,prune='upper'))

旧答案

翻转这两行的顺序:

cb3.update_ticks()
cb3.ax.yaxis.set_major_locator(MaxNLocator(5,prune='upper'))

你应该只有五个颜色间隔。

或者,根本不要使用set_major_locator并在制作实例时直接设置滴答:

cb3 = fig.colorbar(sc2,ax = ax1, aspect=10, ticks=[0, 2.5e-4, 5e-4, 7.5e-4, 1e-3 ])