Plotly offline time series with multiple axis - python

I have a plotly offline chart with datetime and single y axis,now I want to add one more line in y axis.
original code:
from plotly.offline import download_plotlyjs,init_notebook_mode,plot
plot([Scatter(x=datetimefield,y=value1)],filename="plotly.html")
To add multiple I am tried to tweak the y parameter :
plot([Scatter(x=datecolumn,y=[value1,value2])],filename="plotly.html")
But this doesn't seems to be working.
x=datetime field is time series based
y=value1 & value 2 are two pandas columns
Note:- Two axis are in different datatype one is numeric other is percentage
How to tweak the y parameter in offline mode of plotly to have multiple axis.

Found solution:
from plotly.offline import download_plotlyjs,init_notebook_mode,plot
import plotly.graph_objs as go
trace1 = go.Scatter(
x=df.datetimecolumn,
y=df.value1)
trace2 = go.Scatter(
x=df.datetimecolumn,
y=df.value2)
data = [trace1, trace2]
layout = go.Layout(
xaxis=dict(
zeroline=True,
showline=True,
mirror='ticks',
gridcolor='#bdbdbd',
gridwidth=2,
zerolinecolor='#969696',
zerolinewidth=4,
linecolor='#636363',
linewidth=6
),
yaxis=dict(
zeroline=True,
showline=True,
mirror='ticks',
gridcolor='#bdbdbd',
gridwidth=2,
zerolinecolor='#969696',
zerolinewidth=4,
linecolor='#636363',
linewidth=6
)
)
fig = go.Figure(data=data, layout=layout)
plot(fig)

Related

Is there a way to set the values on a Y axis?

I'm trying to create a bar graph using two plots but the Y axis doesn't fit with the y values I have assigned to it (Percent Change). I don't see what I have done wrong when creating the bar graph because when I created a scatter graph with the same approach and assigned values it seemed to be working fine. The y axis should be showing 'percent change' that is 10 or higher. While it does so when a scatter graph is created, it doesn't show these values when creating the bar graph. Instead the bar graph shows the random percent change between 0 and 100 which is not in the assigned values table. Is there any way that I can fix this?
I've copied the code below.
import plotly.graph_objects as go
from plotly.subplots import make_subplots
trace1 = go.Bar(
x=df["Date"],
y=TopTesla["Percent Change"],
name='With Tesla',
text=TopTesla['text'],
marker=dict(
color='rgb(30,160,190)'
)
)
trace2 = go.Bar(
x=df["Date"],
y=TopNotTesla["Percent Change"],
name='Without Tesla',
text=TopNotTesla["text"],
marker=dict(
color='rgb(255,200,35)'
),
yaxis='y2',
offset=100,
showlegend=True
)
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(trace1)
fig.add_trace(trace2,secondary_y=True)
fig['layout'].update(height = 1100, width = 1500,xaxis=dict(
tickangle=-90
))
plt.figure(figsize=[20,25])
iplot(fig)

Plotly - add reversed bar plot to existing normal one

Here's a code:
import plotly
import plotly.express as px
x = data
fig = px.line(x=fruits, y=[1,3,2], color=px.Constant("Line"),
labels=dict(x="Fruit", y="Amount", color="Line"))
fig.add_bar(x=fruits, y=[1,3,1], name="Red")
fig.add_bar(x=fruits, y=[2,1,3], name="Green").update_yaxes(autorange="reversed")
fig.show()
I want to change it, so one bar plot would've been placed normally, and the other would be drawn right opposite the first one, hanging upside down. How can I do it?
Thank you!
You can create a secondary y-axis and reverse the range of values, mapping the first group of bars to the default y-axis, and the second group of bars to the secondary y-axis. Then to make sure the bars don't overlap, you can insert empty data for each group of bars. Also you didn't specify your fruits variable, so I created an arbitrary list for you. Feel free to modify my code to suit your purposes!
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# x = data
fruits = ["apple","pear","orange"]
fig = make_subplots(specs=[[{"secondary_y": True}]])
# fig = px.line(x=fruits, y=[1,3,2], color=px.Constant("Line"),
# labels=dict(x="Fruit", y="Amount", color="Line"))
fig.add_trace(
go.Bar(
x=fruits,
y=[1,3,1],
marker_color="Tomato",
name="Red"
)
)
# empty plot
fig.add_trace(
go.Bar(
x=fruits,
y=[0,0,0],
name=None,
showlegend=False
)
)
# empty values
fig.add_trace(
go.Bar(
x=fruits,
y=[0,0,0],
name=None,
showlegend=False
),
secondary_y=True
)
fig.add_trace(
go.Bar(
x=fruits,
y=[2,1,3],
marker_color="LightGreen",
name="Green",
),
secondary_y=True
)
fig['layout']['yaxis2']['autorange'] = "reversed"
fig.show()

How to show timestamp x-axis in Python Plotly

I want to plot this data to evaluate data availability. I used the following plotting code in Plotly.
import datetime
import plotly.express as px
fig = px.bar(df, x=df.index, y="variable", color='value', orientation="h",
hover_data=[df.index],
height=350,
color_continuous_scale=['firebrick', '#2ca02c'],
title='',
template='plotly_white',
)
The result is just like what I want below.
But, the x-index show numbers. I want a timestamp (month+year) on the x-axis, instead.
Edit
Adding the fllowing
fig.update_layout(yaxis=dict(title=''),
xaxis=dict(
title='Timestamp',
tickformat = '%Y-%b',
)
)
Gives
which seems that the x-axis is not read from the data index.
If you want to use bars it seems to me that you need to find a nice workaround. Have you considered to use Heatmap?
import pandas as pd
import plotly.graph_objs as go
df = pd.read_csv("availability3.txt",
parse_dates=["Timestamp"])\
.drop("Unnamed: 0", axis=1)
# you want to have variable as columns
df = pd.pivot_table(df,
index="Timestamp",
columns="variable",
values="value")
fig = go.Figure()
fig.add_trace(
go.Heatmap(
z=df.values.T,
x=df.index,
y=df.columns,
colorscale='RdYlGn',
xgap=1,
ygap=2)
)
fig.show()

Adding a secondary axis in Plotly Python

I'm working with a Dash graph object and I'm fairly new to it. I'm attempting to pass in a graph that has 2 scatter charts and a bar chart on the same figure but I'd like the bar chart (green) to be on it's own secondary y axis so it looks better than it does here:
Now from what I understand about Dash, I have to pass a go.Figure() object so I have a function which defines the data and the layout. I saw in the plotly documentation that you can use plotly express add secondary axis but I'm not sure how to do that within my frame work here. Any help would be greatly appreciated!
Here's my code:
def update_running_graph(n_intervals):
df = pd.read_csv(filename)
trace1 = go.Scatter(x=df['Timestamp'],
y=df['CLE'],
name='Crude',
mode='lines+markers')
trace2 = go.Scatter(x=df['Timestamp'],
y=df['y_pred'],
name='Model',
mode='lines+markers')
trace3 = go.Bar(x=df['Timestamp'],
y=df['ModelDiff'],
name='Diff',
)
data = [trace1, trace2,trace3]
layout = go.Layout(title='CLE vs Model')
return go.Figure(data=data, layout=layout)
To add a secondary y-axis in dash you could do the following:
def update_running_graph(n_intervals):
df = pd.read_csv(filename)
trace1 = go.Scatter(x=df['Timestamp'],
y=df['CLE'],
name='Crude',
mode='lines+markers',
yaxis='y1')
trace2 = go.Scatter(x=df['Timestamp'],
y=df['y_pred'],
name='Model',
mode='lines+markers',
yaxis='y1')
trace3 = go.Bar(x=df['Timestamp'],
y=df['ModelDiff'],
name='Diff',
yaxis='y2'
)
data = [trace1, trace2,trace3]
layout = go.Layout(title='CLE vs Model',
yaxis=dict(title='Crude and Model'),
yaxis2=dict(title='Moddel Difference',
overlaying='y',
side='right'))
return go.Figure(data=data, layout=layout)
you can add more y-axis they always need to have the form of yi with i the i-th axis. Then in the layout you can specify the layout of the i-th axis with yaxisi=dict(...).
This documentation page should be of use. Just modify to fit your code, since trace1 and trace2 appear to be on the same scale, just set trace3 to the secondary axis scale and you should be set. Below is an example with just only 2 but adding a third should not be too difficult.
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])
# Add traces
fig.add_trace(
go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis data"),
secondary_y=False,
)
fig.add_trace(
go.Scatter(x=[2, 3, 4], y=[4, 5, 6], name="yaxis2 data"),
secondary_y=True,
)
# Add figure title
fig.update_layout(
title_text="Double Y Axis Example"
)
# Set x-axis title
fig.update_xaxes(title_text="xaxis title")
# Set y-axes titles
fig.update_yaxes(title_text="<b>primary</b> yaxis title", secondary_y=False)
fig.update_yaxes(title_text="<b>secondary</b> yaxis title", secondary_y=True)
fig.show()
Cheers!

Histograms grouping by two criteria [python]

I have a dataset like this:
I need to plot this dataset based on two criteria: Churn and Cust_Value.
I can do it using seaborn:
sns.barplot(x="Cust_Value", y="value", hue="Churn", data=merged)
plt.show()
The result gives me:
How can I add all variables (value, age, reloads, calls, duration, sms, gprs, inactive) to the same graph as groups of bars?
for that kind of output i would recommend using plotly,
import plotly.plotly as py
import plotly.graph_objs as go
trace1 = go.Bar(
x=DF['Cust_Value'],
y=DF['value'],
name='value'
)
trace2 = go.Bar(
x=DF['Cust_Value'],
y=DF['age'],
name='age'
)
trace3 = go.Bar(
x=DF['Cust_Value'],
y=DF['calls'],
name='calls'
)
data = [trace1, trace2, trace3]
layout = go.Layout(
barmode='group'
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='grouped-bar')
sample output:
reference: https://plot.ly/python/bar-charts/
hope it helps!
if it does upvote :)
peace

Categories

Resources