Search code examples
pythontime-seriesbokehscatter-plotholoviews

Holoviews colors and colorbar based on datetimes


I am new to holoviews and bokeh and I am trying to create a scatter plot from a time series where the colors are based on the dates. Something similar to the third code cell on this page: https://docs.pymc.io/notebooks/GLM-rolling-regression.html

Does anyone know how to do it?

Ps: I need to use holoviews with a bokeh backend.

Example:
holoviews colorbar based on datetime


Solution

  • I'm solving this by overwriting the tick labels of a colorbar with the dates by using parameter:

     colorbar_opts={
         'major_label_overrides'={}
     }
    

    Here's a working example (simplified):

    # import libraries
    import numpy as np
    import pandas as pd
    import hvplot.pandas
    
    # create sample data
    X = np.random.normal(size=(2, 1000))
    
    df = pd.DataFrame(
        data={
            'col1': X[0],
            'col2': X[1],
            # use 'date' to overwirte the ticklabels of the colorbar
            'date': pd.date_range(start='2017-01-01', freq='D', periods=1000),
        }
    )
    
    # use 'time_color' for the colorbar, since the colors need to be a float or int
    df['time_color'] = df.index.to_series()
    
    
    # draw scatter plot
    # using the 'time_color' column to color the markers
    # and overwrite the tick label using the date column
    
    cbar_opts = dict(
                    major_label_overrides  = df['date'].dt.strftime('%Y-%m-%d').to_dict(),
                    major_label_text_align = 'left',
                    )
    
    hv_coloured = df.hvplot.points(x='col1', y='col2', c='time_color'
                                  ).opts(colorbar_opts=cbar_opts, cmap='viridis')
    
    hv_coloured 
    

    hv_coloured example


    If you do `hv.help(hv.Points)` you can get more explanation on all available options around colorbar:

    colorbar:
    Whether to display a colorbar.

    colorbar_opts:
    Allows setting specific styling options for the colorbar overriding the options defined in the colorbar_specs class attribute. Includes location, orientation, height, width, scale_alpha, title, title_props, margin, padding, background_fill_color and more.

    colorbar_position: Allows selecting between a number of predefined colorbar position options. The predefined options may be customized in the colorbar_specs class attribute.


    This question pointed me in the right direction:

    How do I manually set the tick locations of a colorbar for a Points plot in HoloViews?