简体   繁体   English

Matplotlib Colorbar 更改刻度标签和定位器

[英]Matplotlib Colorbar change ticks labels and locators

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
????

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 (eg, %b%Y or %Y-%m) where the interval could be for example 3 or 6 months.因此,我想将刻度从它们的数值(纳秒?)更改为更合理的日期格式,如月份和年份(例如,%b%Y 或 %Y-%m),其中间隔可以是例如 3 或 6个月。 Is that possible?那可能吗?

I tried to play unsuccessfully with cbar.formatter, cbar.locator and mdates.我尝试使用 cbar.formatter、cbar.locator 和 mdates 失败。

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:您可以保留 colorbar 函数建议的相同定位器,但更改刻度标签以打印格式化日期,如下所示:

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

which gives the result below:结果如下: 格式化日期作为颜色条刻度

If you really want to control tick locations, you can compute the desired values (here for approximately 3 months intervals ~91.25 days):如果你真的想控制刻度位置,你可以计算所需的值(这里大约间隔 3 个月 ~91.25 天):

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

The colormapping machinery of matplotlib has no concepts of "units" like an x or y axis does, so you can do the conversion from date to floats manually before mapping and then set the locator and formatter manually. matplotlib 的颜色映射机制没有像 x 或 y 轴那样的“单位”概念,因此您可以在映射之前手动将日期转换为浮点数,然后手动设置定位器和格式化程序。 You can also look into how pandas maps their date object to floats, it may be a bit different than the native matplotlib mapping:您还可以查看熊猫如何将它们的日期对象映射到浮点数,它可能与原生 matplotlib 映射有点不同:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dates = np.datetime64('2019-11-01') + np.arange(10)*np.timedelta64(1, 'D')
X= np.random.randn(10, 2)

plt.scatter(X[:, 0], X[:, 1], c=mdates.date2num(dates))
cb = plt.colorbar()
loc = mdates.AutoDateLocator()
cb.ax.yaxis.set_major_locator(loc)
cb.ax.yaxis.set_major_formatter(mdates.ConciseDateFormatter(loc))
plt.show()

嘘

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM