Search code examples
pythonmatplotlibplotkernel-density

How to plot kernel density plot but with last column of data frame with dotted line?


I have a dataframe that has values for last 6 weeks. I need to plot kernel density for weekly interval but the last week should be plotted in dotted line.

Here's the dataframe : Weekly data for last 6 weeks : Weekly data for last 6 weeks

Week 1 (10-Mar-2023 to 16-Mar-2023) Week 2 (17-Mar-2023 to 23-Mar-2023) Week 3 (24-Mar-2023 to 30-Mar-2023) Week 4 (31-Mar-2023 to 06-Apr-2023) Week 5 (07-Apr-2023 to 13-Apr-2023) Week 6 (14-Apr-2023 to 20-Apr-2023)
0   167.676448  57.401291   0.000000    32.985973   57.200695   67.172715
1   0.000000    49.341281   0.000000    28.365652   67.744039   58.914095
2   0.000000    56.827458   0.000000    57.531672   64.977708   59.417721
3   0.000000    46.623761   0.000000    31.301324   70.653764   55.513029
4   0.000000    76.401830   0.000000    32.724963   57.221279   56.995764
... ... ... ... ... ... ...
163 59.735175   0.000000    41.558026   57.023258   46.824477   0.000000
164 43.658799   0.000000    49.780197   45.339093   54.183334   0.000000
165 30.453307   0.000000    57.672768   57.958129   40.431805   0.000000
166 57.427614   0.000000    44.916778   36.708974   42.103965   0.000000
167 51.782234   0.000000    39.292057   49.510826   57.774710   0.000000

last5Week_df = weekly_CRF_df[weekly_CRF_df.columns[:-1]]

last5Week_df.plot.density()

lastWeek_df = weekly_CRF_df[weekly_CRF_df.columns[-1:]]

How to add lastWeek_df with previous graph but with dotted line.

I want something like this : weekly kernel density plot


Solution

  • You can plot in two steps, first the initial columns, then the last one:

    ax = last5Week_df.iloc[:, :-1].plot.density(ls='-', legend=False)
    last5Week_df.iloc[:, -1].plot.density(ls=':', ax=ax)
    ax.figure.legend()
    

    Another option, plot all and manually change the last line's style:

    ax = last5Week_df.plot.density(ls='-', legend=False)
    ax.lines[-1].set_linestyle(':')
    ax.legend()
    

    Output:

    enter image description here