I have a set of coordinates that are arranged per year, and I scatterplot them. I create a custom colormap that reflects those years, but the issue is I can’t manage to plot the colorbar of that colormap, and replace the ticks by the values of a numpy array of datetime64. I have no idea how to do it since I don’t plot any image (and the examples online are mainly with plt.imshow).
How could I:
- Plot the colorbar with my custom colormap
- Replace the colorbar’s ticks with my dates ?
This is my code:
JavaScript
x
24
24
1
import matplotlib.dates as mdates
2
import matplotlib.pyplot as plt
3
4
# Create the dates
5
dates = np.datetime64('2017') + np.arange(5)*np.timedelta64(1, 'Y')
6
7
# Create array where the dates are the 2nd dimension
8
arr = np.random.randn(3,5,10,2)
9
colors = cm.seismic(np.linspace(0,1, num=arr.shape[1]))
10
fig,ax = plt.subplots()
11
12
# Iterate through the 1st and 2nd dimension
13
for g in range(0,arr.shape[0]):
14
for i in range(0,arr.shape[1]):
15
plot = plt.scatter(arr[g,i,:,0],arr[g,i,:,1], s = 10, marker = '_', color = colors)
16
17
# Attempt to plot the colorbar and replace ticks by the years
18
cb = plt.colorbar()
19
loc = mdates.AutoDateLocator()
20
cb.ax.yaxis.set_major_locator(loc)
21
cb.ax.yaxis.set_major_formatter(mdates.ConciseDateFormatter(loc))
22
23
colors
24
Advertisement
Answer
JavaScript
1
37
37
1
import matplotlib.dates as mdates
2
import matplotlib.pyplot as plt
3
import matplotlib.cm as cm
4
from matplotlib.colors import Normalize
5
import numpy as np
6
7
# Create the dates
8
dates = np.datetime64('2017') + np.arange(5)*np.timedelta64(1, 'Y')
9
10
# Create array where the dates are the 2nd dimension
11
arr = np.random.randn(3,5,10,2)
12
values = np.linspace(0,1, num=arr.shape[1])
13
14
# create a normalizer
15
norm = Normalize(vmin=values.min(), vmax=values.max())
16
# normalize values
17
norm_values = norm(values)
18
# choose a colormap
19
cmap = cm.seismic
20
# create colors
21
colors = cmap(norm_values)
22
# map values to a colorbar
23
mappable = cm.ScalarMappable(norm=norm, cmap=cmap)
24
mappable.set_array(values)
25
26
fig, ax = plt.subplots()
27
28
# Iterate through the 1st and 2nd dimension
29
for g in range(0,arr.shape[0]):
30
for i in range(0,arr.shape[1]):
31
plot = plt.scatter(arr[g,i,:,0],arr[g,i,:,1], s = 10, marker = '_', color = colors[i])
32
33
# replace ticks by the years
34
cb = fig.colorbar(mappable, ticks=values)
35
cb.ax.set_yticklabels(dates)
36
cb.set_label("Date")
37