Search code examples
python-3.xmatplotlibvisualizationbokeh

Show different classification classes as different colors on a timeseries plot


I want to visualize a line plot of time series with different classes in the background in python.

Suppose if I have time series of 5 minutes with 3 classes as shown in the table 1.

Time start Time End Class
00:00:00 00:00:30 1
00:00:31 00:01:30 2
00:01:31 00:04:00 3
00:04:01 00:05:00 2

I also have pressure values every 10 seconds shown in table 2.

Time End Pressure
00:00:10 0.2
00:00:20 0.3
00:00:30 0.53
. .
. .
00:04:50 0.7
00:05:00 0.92

I want to plot a line graph on top of the classes with different colors as shown in the figure below. The line plot follows the table 2 and the background color of the line plot follows table 1. enter image description here

I am open to use any python library that could help me complete this visualization.


Solution

  • You can use the following snippet:

    # convert timestamp to seconds
    df2['Time End'] = pd.to_timedelta(df2['Time End']).dt.total_seconds()
    df1['Time start'] = pd.to_timedelta(df1['Time start']).dt.total_seconds()
    df1['Time End'] = pd.to_timedelta(df1['Time End']).dt.total_seconds()
    
    # plot line
    ax = df2.plot(x='Time End', y='Pressure')
    ax.set_ylabel('Pressure')
    
    # plot spans
    colors = {1: '#D9E8FB', 2: '#F7CECC', 3: '#FFF2CD'}
    for _, (x1, x2, c) in df1.iterrows():
        ax.axvspan(x1, x2, color=colors[c])
    

    line plot with vspans