Search code examples
matplotlibcolorbar

How do I plot a continuous color bar instead of discrete?


I am contouring some 2D data but want to have a continuous color bar instead of a discrete. How do I get this? Check out my code and output.

I have tried plotting without providing color levels, different color maps but does not help.

    ylim = [0, 8]
    xlim = [starttime, endtime]
    fig = plt.figure(figsize=(10,7))
    ax = plt.subplot()

    levels1 = np.arange(5,61,5)
    cmap=plt.get_cmap('jet')
    Zplot=ax.contourf(timesNew, hgtNew, ZNew, levels1, cmap=cmap,
                    vmin=min(levels1), vmax=max(levels1), extend='both')
    cbZ=plt.colorbar(Zplot, ticks=levels1)

    niceDates = []
    for timestamp in np.arange(ax.get_xlim()[0],ax.get_xlim()[1]+sec,sec):
       niceDates.append(str(datetime.datetime.utcfromtimestamp(timestamp).strftime("%H")))
    ax.set_ylim(ylim)
    ax.set_xlim(xlim)
    ax.set_xticks(np.arange(ax.get_xlim()[0],ax.get_xlim()[1]+sec,sec))
    ax.set_xticklabels([])
    ax.set_xticklabels(niceDates) #plot nice dates
    ax.set_ylabel('Height (km)', fontsize=labelsize)
    ax.set_xlabel('Time (UTC)', fontsize=labelsize)

The code works and plots nicely but the color bar is discrete and I want it to be continuous. What am I doing wrong? The data is in 2D numpy arrays. I have done some extensive processing to the data so not showing the full code other than the plotting. Example output from above code


Solution

  • As far as I know there is no way to get a real continuous colorbar. Try adding a lot more levels. This way it will look more like a continuous colorbar.

    ylim = [0, 8]
    xlim = [starttime, endtime]
    fig = plt.figure(figsize=(10,7))
    ax = plt.subplot()
    
    levels1 = np.linspace(5,61,500)
    level_ticks = np.arange(5, 61, 5)
    cmap=plt.get_cmap('jet')
    Zplot=ax.contourf(timesNew, hgtNew, ZNew, levels1, cmap=cmap,
                    vmin=min(levels1), vmax=max(levels1), extend='both')
    
    cbZ=plt.colorbar(Zplot, ticks=level_ticks)
    
    niceDates = []
    for timestamp in np.arange(ax.get_xlim()[0],ax.get_xlim()[1]+sec,sec):
       niceDates.append(str(datetime.datetime.utcfromtimestamp(timestamp).strftime("%H")))
    ax.set_ylim(ylim)
    ax.set_xlim(xlim)
    ax.set_xticks(np.arange(ax.get_xlim()[0],ax.get_xlim()[1]+sec,sec))
    ax.set_xticklabels([])
    ax.set_xticklabels(niceDates) #plot nice dates
    ax.set_ylabel('Height (km)', fontsize=labelsize)
    ax.set_xlabel('Time (UTC)', fontsize=labelsize)