Python: How to create a step plot with offline plotly for a pandas DataFrame?
Question:
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"] )]})
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:
Question
How can I get same results as step
function but using offline
plotly
instead?
Answers:
As your data is a pandas dataframe, alternatively to offline plotly, you could use plotly express:
import plotly.express as plx
plx.line(df,line_shape='hv')
Other line_shape options, or interpolation methods between given points:
- ‘hv’ step ends, equivalent to pyplot’s post option;
- ‘vh’ step starts;
- ‘hvh’ step middles, x axis;
- ‘vhv’ step middles, y axis;
- ‘spline’ smooth curve between points;
- ‘linear’ line segments between points, default value for line_shape.
Just try them…
hv = plx.line(df,line_shape='hv')
vh = plx.line(df,line_shape='vh')
vhv = plx.line(df,line_shape='vhv')
hvh = plx.line(df,line_shape='hvh')
spline = plx.line(df,line_shape='spline')
line = plx.line(df,line_shape='linear')
Selection of one of them should be commited to the nature of your data…
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"] )]})
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:
Question
How can I get same results as step
function but using offline
plotly
instead?
As your data is a pandas dataframe, alternatively to offline plotly, you could use plotly express:
import plotly.express as plx
plx.line(df,line_shape='hv')
Other line_shape options, or interpolation methods between given points:
- ‘hv’ step ends, equivalent to pyplot’s post option;
- ‘vh’ step starts;
- ‘hvh’ step middles, x axis;
- ‘vhv’ step middles, y axis;
- ‘spline’ smooth curve between points;
- ‘linear’ line segments between points, default value for line_shape.
Just try them…
hv = plx.line(df,line_shape='hv')
vh = plx.line(df,line_shape='vh')
vhv = plx.line(df,line_shape='vhv')
hvh = plx.line(df,line_shape='hvh')
spline = plx.line(df,line_shape='spline')
line = plx.line(df,line_shape='linear')
Selection of one of them should be commited to the nature of your data…