Search code examples
pythonmatplotlibcolorbar

Colorbar showing time of the day


I am working on scatter plots. I am plotting the colormap based on the time of the day. The problem is the colorbar shows the time as an hour fraction, not as time.

My code:

plt.scatter(df[x], df[y], c=df.index.hour+df.index.minute/60, cmap='jet')
plt.colorbar()
plt.show()

enter image description here

The above color bar shows the time as a fraction. For instance, I'd like to show 17:30 instead of 17.5.


Solution

  • You can set an explicit tick formatter for the colorbar. For example (tested with matplotlib 3.3.1):

    plt.colorbar(format=lambda t, pos: f'{math.floor(t):02.0f}:{(t*60)%60:02.0f}')
    

    example plot

    PS: Another way to set the tick formatter, which might also work with older matplotlib versions, is to explicitly set a FuncFormatter:

    cbar = plt.colorbar()
    cbar.ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda t, pos: f'{math.floor(t):02.0f}:{(t*60)%60:02.0f}'))
    

    Or also:

    plt.colorbar(format=plt.FuncFormatter(lambda t, pos: f'{math.floor(t):02.0f}:{(t*60)%60:02.0f}'))