Home > Net >  add vertical lines to plot at dates where column contains text
add vertical lines to plot at dates where column contains text

Time:10-27

import plotly as plotly
from plotly.offline import plot
import plotly.express as px
import plotly.graph_objects as go

import pandas as pd
import numpy as np

df = pd.DataFrame({'height': [712, 712, 716, 716, 718, np.nan, np.nan, np.nan, np.nan, np.nan],
                           'moisture': [0.06, 0.19, 0.18, 0.17, 0.18, np.nan, np.nan, np.nan, np.nan, np.nan],
                           'tasks': ['water', None, None, 'prune', None, None, 'position', None, 'prune', None]}, 
                           index=['2020-01-04', '2020-01-05', '2020-01-06', '2020-01-07', '2020-01-08', '2020-01-09',
                            '2020-01-10', '2020-01-11', '2020-01-12', '2020-01-13'])

df.index.name = 'date'

From the df I want to plot a 'line' graph and add vertical lines at all index date points where a value appears in df.tasks column irrespective whether there is a value in the corresponding height row or not.

I am able to plot the 'line' grapgh only with the basic line representing the height values but not the verticals, using .....

fig = px.line(df, x=df.index, y=df.height)

After this I created dictionary from which I think the vertical lines from could be generated from....

index_tasks = df[~df.tasks.isnull()]


task_dict = index_tasks.groupby('date')['tasks'].apply(list).to_dict() 

However, even after exploring the plotly documentation, I am not sure how to proceed.

Thank you for reading and hopefully you can lend a helping hand.

CodePudding user response:

  • you really described what needs to be coded
  • in plotly shapes of which a vline is a type of shape are part of the layout not the trace. Hence simplest way is to add them after figure is created.
import plotly as plotly
from plotly.offline import plot
import plotly.express as px
import plotly.graph_objects as go

import pandas as pd
import numpy as np

df = pd.DataFrame({'height': [712, 712, 716, 716, 718, np.nan, np.nan, np.nan, np.nan, np.nan],
                           'moisture': [0.06, 0.19, 0.18, 0.17, 0.18, np.nan, np.nan, np.nan, np.nan, np.nan],
                           'tasks': ['water', None, None, 'prune', None, None, 'position', None, 'prune', None]}, 
                           index=['2020-01-04', '2020-01-05', '2020-01-06', '2020-01-07', '2020-01-08', '2020-01-09',
                            '2020-01-10', '2020-01-11', '2020-01-12', '2020-01-13'])


fig = px.line(df, y="height")

for x in df.loc[~df["tasks"].isna()].index:
    fig.add_vline(x=x)
fig.show()

enter image description here

  • Related