Search code examples
pythonmatplotlibcolorbar

how to set sequential positive colorbar range with lowest value in the middle of colorbar


I am trying to set a colorbar, and I understand clim can do that. I cannot figure out how you set it so that the middle colorbar value is the smallest 1, with for example, a range of 1 to 52?

I am doing this because I have week numbers, but I do not want to show big jumps in the color from December to January (values 52 and 1)

EDIT: I am talking about the colors so that the ends of the colorbar are similar in color but the middle is the most different color. I do not want to change the values in the colorbar


Solution

  • What you're asking for is a cyclic colormap. As of now, matplotlib only provides one single cyclic colormap, namely "hsv". You may however define your own colormap easily and make sure it's cyclic, e.g. using the colors ["gold", "red", "black", "navy", "gold"] where the first and the last color are the same.

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    plt.rcParams['lines.markersize'] = 12
    
    x = np.arange(200)
    y = np.ones(200)
    
    fig, ax = plt.subplots()
    ax.scatter(x,y, c=x % 52, marker="|" )
    
    ax.scatter(x,y-1, c=x % 52, cmap="hsv", marker="|" )
    
    colors = ["gold", "red", "black", "navy", "gold"]
    cmap = mcolors.LinearSegmentedColormap.from_list("", colors)
    ax.scatter(x,y-2, c=x % 52, cmap=cmap, marker="|" )
    
    ax.set_yticks([-1,0,1])
    ax.set_yticklabels(["custom", "hsv", "viridis", ])
    ax.margins(y=0.4)
    plt.show()
    

    enter image description here