Home > Net >  Plot multiple lines into the same chart over time from pandas group by result using plotly
Plot multiple lines into the same chart over time from pandas group by result using plotly

Time:06-17

I want to plot multiple lines in the same chart over time from a pandas groubby result. My data looks the following

import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df['Date']=pd.to_datetime(df['Date'])

Now I am grouping my data by month and direction

df.groupby([pd.Grouper(key='Date', freq='M'), 'direction'])

Which gives me

Date        direction
2015-02-28  Decreasing     4
            Increasing     5
2015-03-31  Decreasing    14
            Increasing     8
2015-04-30  Decreasing    12
            Increasing     9
2015-05-31  Decreasing    10
....

How would I plot this in a line chart? On the x-Axis I want the time, on the y-Axis the count and for each group within direction I want a line. Preferably using Plotly.

CodePudding user response:

I don't have the expected graph, so I understood from the comments that the graph was to be a line chart of a time series with two different line types. I used a graph object and a loop process to graph the line mode of the scatter plot in the directional units.

dfg = df.groupby([pd.Grouper(key='Date', freq='M'), 'direction']).size().to_frame('counts')
dfg.reset_index(inplace=True)
dfg.head()
Date    direction   counts
0   2015-02-28  Decreasing  4
1   2015-02-28  Increasing  5
2   2015-03-31  Decreasing  14
3   2015-03-31  Increasing  8
4   2015-04-30  Decreasing  12

import plotly.graph_objects as go

fig = go.Figure()

for d,c in zip(dfg['direction'].unique(), ['red','green']):
    dfs = dfg.query('direction == @d')
    fig.add_trace(
        go.Scatter(
            x=dfs['Date'],
            y=dfs['counts'],
            mode='lines',
            line=dict(
                color=c,
                width=3
            ),
            name=d
        )
    )

fig.show()

enter image description here

  • Related