Home > Back-end >  Endvalues of colorbands on a plot using Matplotlib
Endvalues of colorbands on a plot using Matplotlib

Time:09-06

How do I ensure that the colorbar has all the end values for each colorband? For example, in the current output, the greyband has no end value. I present the expected output where the greyband has the end value i.e. 5.4035. More generally, I want a command which enables all the values of the colorbands.

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
from matplotlib.colors import Normalize
from matplotlib import cm
import math


fig,ax = plt.subplots(1)
n=3


N=2*n*(n-1)

p=np.array([[0.0000535              , 0.000051590914956234785,
        0.00005031819159372464 , 0.00005286363831874494 ,
        0.000052227276637489866, 0.00004904546823121452 ,
        0.000049681829912469585, 0.00004650002150619425 ,
        0.00004777274486870438 , 0.00004713638318744931 ,
        0.00005095455327497972 , 0.000054035            ]])


p=p.reshape(12,1)           
P = np.array(p)
P=P.reshape(len(P),1)

Max=max(P)

Min=min(P)

a=Min
b=Max



Amax= b*math.ceil(Max)
print("Amax =",Amax)
Amin= a*math.floor(Min/a)
print("Amin =",Amin)



color = cm.get_cmap('Dark2')
norm = Normalize(vmin=Amin, vmax=Amax)
color_list = []
for i in range(len(P)):
    color_list.append(color((P[i]-Amin)/(Amax-Amin)))
    #color_list.append(color(((P[0,i])-Amin)/(Amax-Amin)))

id = 0
for j in range(0, n):
    for k in range(n-1):
        ax.hlines(200 200*(n-j-1) 5*n, 200*(k 1) 5*n, 200*(k 2) 5*n, zorder=0, colors=color_list[id])
        id  = 1

    for i in range(0, n):
        rect = mpl.patches.Rectangle((200 200*i, 200 200*j), 10*n, 10*n, linewidth=1, edgecolor='black', facecolor='black')
        ax.add_patch(rect)
        if j < n-1:
            ax.vlines(200 200*i 5*n, 200*(n-1-j) 5*n, 200*(n-j) 5*n, zorder=0, colors=color_list[id])
            id  = 1

cb = fig.colorbar(cm.ScalarMappable(cmap=color, norm=norm))


cb.set_ticks(np.arange(Amin, Amax, (Amax-Amin)/8).astype(float))
cb.set_label("Radius (m)")
ax.set_xlim(left = 0, right = 220*n)
ax.set_ylim(bottom = 0, top = 220*n)

plt.axis('off')

plt.show()

The current output is

enter image description here

The expected output is

enter image description here

CodePudding user response:

As you want to add the last number (5.4e-05), you can set the Amax to just a little higher than the current number, but keeping the number of ticks at 8, it will work. If you replace the set_ticks() like this

cb.set_ticks(np.arange(Amin, Amax 0.1e-05, (Amax-Amin)/8).astype(float))

Plot

enter image description here

  • Related