matplotlib颜色条刻度标签格式

matplotlib颜色条刻度标签格式

本文介绍了matplotlib颜色条刻度标签格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在matplotlib中显式设置颜色条对象的格式

I am wondering how I can explicitly set the format of a colorbar object in matplotlib

这是一个绘图脚本示例:

Here is an example plotting script:

from matplotlib import pyplot
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
from pylab import *
import numpy as np
import random

# ----------

plot_aspect = 1.2
plot_height = 10.0
plot_width = int(plot_height*plot_aspect)

# ----------

pyplot.figure(figsize=(plot_width, plot_height), dpi=100)
pyplot.subplots_adjust(left=0.10, right=1.00, top=0.90, bottom=0.06, hspace=0.30)
subplot1 = pyplot.subplot(111)

# ----------

cbar_max = 40.0
cbar_min = 20.0
cbar_step = 1.0
cbar_num_colors = 200
cbar_num_format = "%d"

# ----------
# make random dataset

dx, dy = 5.0, 5.0
y, x = np.mgrid[slice(-100.0, 100.0 + dy, dy),slice(-100.0, 100.0 + dx, dx)]

z = []
for i in x:
    z.append([])
    for j in y:
        z[-1].append(random.uniform(cbar_min,cbar_max))

# ----------
# make random dataset

levels = MaxNLocator(nbins=cbar_num_colors).tick_values(cbar_min, cbar_max)
cmap = pyplot.get_cmap('gist_ncar')
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
pp = pyplot.contourf(x,y,z,levels=levels,cmap=cmap)
cbar = pyplot.colorbar(pp, orientation='vertical', ticks=np.arange(cbar_min, cbar_max+cbar_step, cbar_step), format=cbar_num_format)
cbar.ax.set_ylabel('Color Scale [unit]', fontsize = 16, weight="bold")

CS = pyplot.contour(x,y,z, alpha=0.5)

majorLocator1   = MultipleLocator(10)
majorFormatter1 = FormatStrFormatter('%d')
minorLocator1   = MultipleLocator(5)

subplot1.xaxis.set_major_locator(majorLocator1)
subplot1.xaxis.set_major_formatter(majorFormatter1)
subplot1.xaxis.set_minor_locator(minorLocator1)

pyplot.xticks(fontsize = 16)
pyplot.xlim(-100.0,100.0)

majorLocator2   = MultipleLocator(10)
majorFormatter2 = FormatStrFormatter('%d')
minorLocator2   = MultipleLocator(5)

subplot1.yaxis.set_major_locator(majorLocator2)
subplot1.yaxis.set_major_formatter(majorFormatter2)
subplot1.yaxis.set_minor_locator(minorLocator2)

pyplot.yticks(fontsize = 16)
pyplot.ylim(-100.0,100.0)

subplot1.xaxis.grid()
subplot1.yaxis.grid()
subplot1.axes.set_aspect('equal')

pyplot.suptitle('Main Title', fontsize = 24, weight="bold")

pyplot.xlabel('X [unit]', fontsize=16, weight="bold")
pyplot.ylabel('Y [unit]', fontsize=16, weight="bold")

pyplot.show()
pyplot.close()

这给了我这样的输出:

当前,颜色条刻度标签的格式将使用前面提供的格式字符串: cbar_num_format =%d" ,但是我也想使用以下命令设置字体大小和粗细:

Currently the colorbar tick label formatting will use the format string provided earlier: cbar_num_format = "%d", but I'd like to also set the font size and weight using:

cbar.ax.set_yticklabels(np.arange(cbar_min, cbar_max+cbar_step, cbar_step), fontsize=16, weight='bold')

...但是,当我这样做时,以前应用的格式化程序字符串似乎消失了,并且数字以%0.1f" 格式代替了%d"我之前应用的:

...but when I do this, the previously applied formatter string seems to go away and the numbers are back in "%0.1f" format instead of the "%d" that I applied earlier:

如何防止这种情况发生或更好地控制颜色条刻度标签?

How can I prevent this from happening or control the colorbar tick labeling in a better way?

推荐答案

一个选项是仅手动设置刻度标签的格式.也许有更好的方法,但这通常对我有用.

One option is to just format the ticklabels manually. There is probably a better way but this usually works for me.

cbar.ax.set_yticklabels(['{:.0f}'.format(x) for x in np.arange(cbar_min, cbar_max+cbar_step, cbar_step)], fontsize=16, weight='bold')

如果您不想自己找出刻度,可以使用:

If you don't want to figure out the ticks yourself you can use:

for l in cbar.ax.yaxis.get_ticklabels():
    l.set_weight("bold")
    l.set_fontsize(16)

如果它们未正确更新,则可能需要调用 draw().可以使用以下方法将其减少为一个衬板:

You may need to call draw() if they are not properly updated. This can be reduced to a one liner with:

setp(cbar.ax.yaxis.get_ticklabels(), weight='bold', fontsize=16)

这篇关于matplotlib颜色条刻度标签格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 08:48