Matplotlib Colorbar更改刻度标签和定位器 [英] Matplotlib Colorbar change ticks labels and locators

查看:54
本文介绍了Matplotlib Colorbar更改刻度标签和定位器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改下图的颜色栏中的刻度线定位器和标签.

I would like to change the ticks locators and labels in the colorbar of the following plot.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
import numpy as np

# fontdict to control style of text and labels
font = {'family': 'serif',
        'color':  (0.33, 0.33, 0.33),
        'weight': 'normal',
        'size': 18,
        }

num = 1000
x = np.linspace(-4,4,num) + (0.5 - np.random.rand(num))
y = np.linspace(-2,2,num) + (0.5 - np.random.rand(num))
t = pd.date_range('1/1/2014', periods=num)

# make plot with vertical (default) colorbar
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 6))
ax.set_title('Scatter plot', fontdict=font)

# plot data
s = ax.scatter(x = x, y = y, 
               s=50, c=t, marker='o', 
               cmap=plt.cm.rainbow)

# plot settings
ax.grid(True)
ax.set_aspect('equal')
ax.set_ylabel('Northing [cm]', fontdict=font)
ax.set_xlabel('Easting [cm]', fontdict=font)

# add colorbar
cbar = fig.colorbar(mappable=s, ax=ax)
cbar.set_label('Date')

# change colobar ticks labels and locators
????

颜色栏说明了时间依赖性.因此,我想将刻度线的数值(纳秒?)更改为更明智的日期格式,例如月份和年份(例如,%b%Y或%Y-%m),其中间隔可以为3或6个月.有可能吗?

The colorbar illustrates the time dependency. Thus, I would like to change the ticks from their numerical values (nanoseconds?) to more sensible date format like months and year (e.g., %b%Y or %Y-%m) where the interval could be for example 3 or 6 months. Is that possible?

我尝试使用cbar.formatter,cbar.locator和mdates失败.

I tried to play unsuccessfully with cbar.formatter, cbar.locator and mdates.

推荐答案

您可以保留与colorbar函数建议的定位器相同的定位器,但可以更改刻度线标签,以便按以下方式打印格式化的日期:

You can keep the same locators as proposed by the colorbar function but change the ticklabels in order to print the formatted date as follows:

# change colobar ticks labels and locators 
cbar.set_ticks([s.colorbar.vmin + t*(s.colorbar.vmax-s.colorbar.vmin) for t in cbar.ax.get_yticks()])
cbar.set_ticklabels([mdates.datetime.datetime.fromtimestamp((s.colorbar.vmin + t*(s.colorbar.vmax-s.colorbar.vmin))/1000000000).strftime('%c') for t in cbar.ax.get_yticks()])
plt.show()

给出以下结果:

如果您真的想控制刻度位置,则可以计算所需的值(此处大约每3个月间隔〜91.25天):

If you really want to control tick locations, you can compute the desired values (here for approximately 3 months intervals ~91.25 days):

i,ticks = 0,[s.colorbar.vmin]
while ticks[-1] < s.colorbar.vmax:
   ticks.append(s.colorbar.vmin+i*24*3600*91.25*1e9)
   i = i+1
ticks[-1] = s.colorbar.vmax
cbar.set_ticks(ticks)
cbar.set_ticklabels([mdates.datetime.datetime.fromtimestamp(t/1e9).strftime('%c') for t in ticks])

这篇关于Matplotlib Colorbar更改刻度标签和定位器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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