0

I have tried the method from this question but it does not work, because the shape of my array is 3D, whereas the shape they use is 2D.

I begin with a 3-dimensional array

import numpy as np
import matplotlib.pyplot as plt

ins = np.load('ins.npy')
ex = ins[1]
ex.shape
# (60,60,1)

Now I plot the image.

ax = plt.gca()
im = ax.imshow(ex)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)

I've searched for hours and, though this seems very simple, I haven't been able to find a way to create my own colorbar. I would like to use a colorscheme similar to the one employed by the weather service. The ticks would be:

ticks = [20,35,45,55,65,75]

I've tried doing:

x = [20,35,45,55,65,75]
colors = ["#eaa941", "#efef39", "#53a447", "#3b387f", "#48a2ba"]
cmap= mpl.colors.ListedColormap(colors)
cmap.set_under("crimson")
cmap.set_over("w")
norm= mpl.colors.Normalize(vmin=0,vmax=-70)   

im = ax.contourf(x,x,ex, levels=[20,35,45,55,65,75],extend='both',cmap=cmap,norm=norm)

But no luck.

McM
  • 471
  • 5
  • 21
  • The issue is with the way you have created the the `cotourf`: `x,x,ex` do not seem to be correctly defined. The duplicate works fine, as it is implemented the same way with the examples shown at [matplotlib: `matplotlib.axes.Axes.contourf`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.contourf.html) – Trenton McKinney Sep 01 '21 at 04:13
  • In response to _I have tried the method from this question but it does not work_. Here's a simple example directly from the docs, which then uses the duplicate to add a colorbar. `x = np.arange(0, 100); y = x.reshape(-1, 1); h = x * y; cs = plt.contourf(h, levels=[20,35,45,55,65,75], colors=["#eaa941", "#efef39", "#53a447", "#3b387f", "#48a2ba"], extend='both'); plt.colorbar(cs, ticks=bounds)` – Trenton McKinney Sep 01 '21 at 04:17
  • 1
    @TrentonMcKinney Oh, wow. It works now. Huh. Yea I think I was missing the bounds argument and incorrectly pointing to ```x```. Gosh, that gave me such a headache! Thanks! – McM Sep 01 '21 at 04:42
  • Glad it worked for you. – Trenton McKinney Sep 01 '21 at 04:42
  • @TrentonMcKinney Actually, I've found the problem. I have to transform an array from ```(1, 3600)``` to the shape ```(60,60,1)```, but the contourf function only takes 2D fields. If I simply reshape my array into ```(60,60)``` the image is lost. I think it's folded in wrong or... I'm not sure – McM Sep 01 '21 at 04:57
  • I think how to correctly shape the arrays, might be a different question. You should create a new question, but be sure to provide a sufficient example of your data, that someone can answer the question, and show what you've tried. – Trenton McKinney Sep 01 '21 at 04:59

0 Answers0