Search code examples
pythonpandasdataframeplotplotly

Python: How to create a step plot with offline plotly for a pandas DataFrame?


Lets say we have following DataFrame and corresponding graph generated:

import pandas as pd
import plotly
from plotly.graph_objs import Scatter

df = pd.DataFrame({"value":[10,7,0,3,8]},
index=pd.to_datetime([
"2015-01-01 00:00",
"2015-01-01 10:00",
"2015-01-01 20:00",
"2015-01-02 22:00",
"2015-01-02 23:00"]))
plotly.offline.plot({"data": [Scatter( x=df.index, y=df["value"] )]})

plotly graph

Expected results

If I use below code:

import matplotlib.pyplot as plt
plt.step(df.index, df["value"],where="post")
plt.show()

I get a step graph as below:

step graph

Question

How can I get same results as step function but using offline plotly instead?


Solution

  • We can use the line parameter shape option as hv using below code:

    trace1 = {
      "x": df.index,
      "y": df["value"],
      "line": {"shape": 'hv'},
      "mode": 'lines',
      "name": 'value',
      "type": 'scatter'
    };
    
    data = [trace1]
    plotly.offline.plot({
        "data": data
    })
    

    Which generates below graph:

    enter image description here