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)
Related
I'm trying to add a point to the last observation on a time series chart with plotly. It is not very different from the example here https://stackoverflow.com/a/72539011/3021252 for instance. Except it is the last observation. Unfortunately following such pattern modifies the axis range.
Here is an example of an original chart
import plotly.express as px
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
fig.show()
But after adding a marker
import plotly.graph_objects as go
fig.add_trace(
go.Scatter(
x=[df["year"].values[-1]],
y=[df["lifeExp"].values[-1]],
mode='markers'
)
)
It looks like that
Has anyone have an idea how not to introduce this gap on the right?
Here is CDF visualization I have:
fig_cdf = px.ecdf(df['Timespan'], color_discrete_sequence=['blue'],ecdfnorm='probability', orientation='h')
fig_cdf.add_hline(y=90, line_width=2, line_color="red", name='90%', visible=True)
fig_cdf.add_hline(y=30, line_width=2, line_color="red", name='75%', visible=True)
fig_cdf.update_layout(width=500, height=500)
The problem here is that i want horizontal lines' names to be visible and appear as 2nd and 3rd legends. For this, I tried to add visible=True. However, it seems not to work. What's wrong?
This is one way of doing it...
Add the two lines to the dataframe as new columns
Use color_discrete_sequence to identify the colors you want
I am using some random dummy data, which you can replace with your data
import plotly.express as px
df = pd.DataFrame({'firstline': random.sample(range(1, 500), 20),'myX' : range(20)}) #My dummy data
#Add the two lines to dataframe
df['90%'] = [90] * 20
df['75%'] = [75] * 20
fig = px.line(df,
y = ['firstline', '90%', '75%'], x= 'myX', color_discrete_sequence=["blue", "red", "red"])
fig.update_layout(legend_title_text='Legend Heading') #Update Legend header if you dont like 'variable'
fig.show()
Output graph
This is my first experience with this graph, but to add it to the legend, you can use the line mode of the scatter plot. So I took the maximum x-axis value used in the first graph and set the legend name Average using the appropriate y-axis value. This example is taken from the official reference.
import plotly.express as px
import plotly.graph_objects as go
df = px.data.tips()
fig = px.ecdf(df, x=["total_bill", "tip"])
xmax = max(fig.data[0]['x'])
#print(xmax)
fig.add_trace(go.Scatter(
x=[0,xmax],
y=[0.6,0.6],
mode='lines',
line_color='red',
name='mean',
showlegend=True
))
fig.show()
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()
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!
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)