I try to put scatter plot with secondary axis into Dash app and getting strange error. I tried many option but not sucsess... maybe you see whats wrong.
This is my code:
def scatter_1() -> dcc.Graph:
return dcc.Graph(
id="scatter-1",
figure2 = make_subplots(specs=[[{"secondary_y": True}]])
# Add traces
figure2.add_trace(
go.Scatter(set_df_f(),x="Testmantime", y="Speed1[Rpm]", name="yaxis data"),
secondary_y=False,
)
figure2.add_trace(
go.Scatter(set_df_f(),x="Testmantime", y='dda_50Amplitude', name="yaxis2 data"),
secondary_y=True,
)
# Add figure title
figure2.update_layout(
title_text="Double Y Axis Example"
)
# Set x-axis title
figure2.update_xaxes(title_text="xaxis title")
# Set y-axes titles
figure2.update_yaxes(title_text="<b>primary</b> yaxis title", secondary_y=False)
figure2.update_yaxes(title_text="<b>secondary</b> yaxis title", secondary_y=True)
)
Error in VSC says:
"(" was not closed",Pylance",LINE 31
line 31 is second line in the code i pasted: return dcc.Graph(
I dont get it, same syntax in jupyter work fine (difference is funcion import of dataframe). Appriciate your help.
Paulina
Related
Hello guys i need help i have a piece of code that adds a list of horizontal lines to a Plotly figure in python. i want to change the code to were we will use a slider to add the horizontal lines to the figure and relayout it. As the slider moves right more horizontal lines will be added to the figure when the slider moves left the horizontal lines will be removed from the figure. Below is the bit of my code so far
for v in range(len(sortadlist)):
fig.add_hline(y=sortadlist[v][0], line_color='brown', line_width=1.5, row=1, col=1)
fig.add_shape(type="rect",
y0=round(sortadlist[v][0],2)-.3, y1=round(sortadlist[v][0],2)+.3, x0=-1, x1=len(df),
fillcolor="darkcyan",
opacity=0.15)
All the code above does is loop through a list of numbers and uses the fig.add_hline to add the horizontal line to the figure. I need help creating a slider that will add the horizontal lines to the figure
This is how the figure currently looks i want a slider to help with adding more horizontal lines to the figure and remove them also
Since the entire code is not available, the sample data was handled by obtaining the company's stock price. First of all, horizontal lines and shapes do not have a show/hide attribute, so they are not compatible with sliders. So I have created a code to draw a line according to the appropriate price list in the line chart of the scatter chart. Once the line chart is hidden, the first line chart is made visible.
The structure of the graph is a candlestick with 6 lines and the candlestick is always displayed. A loop process is used to create a list of lines to be shown or hidden.
import yfinance as yf
import plotly.graph_objects as go
import numpy as np
df = yf.download("AAPL", start="2022-01-01", end="2023-01-01", progress=False)
df.reset_index(inplace=True)
pricelist = np.arange(130,190,10)
fig = go.Figure()
fig.add_trace(go.Candlestick(x=df['Date'],
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'],
name='AAPL'
)
)
fig.add_hrect(y0=df['Close'].median()-10,
y1=df['Close'].median()+10,
annotation_text="Median+-10",
annotation_position="top right",
fillcolor="darkcyan",
opacity=0.25,
line_width=0)
for p in pricelist:
fig.add_trace(go.Scatter(x=df['Date'],
y=[p]*len(df['Date']),
line_color='blue',
name=str(p),
showlegend=False,
visible=False,
)
)
fig.data[1].visible = True
steps = []
for i in np.arange(1,len(fig.data)):
step = dict(
method="update",
args=[{"visible": [False] * len(fig.data)},
{"title": "Price lines: " + str(pricelist[i-1])}],
label=str(pricelist[i-1])
)
step["args"][0]["visible"][0] = True
step["args"][0]["visible"][i] = True
steps.append(step)
sliders = [dict(
active=10,
currentvalue={"prefix": "Price: "},
pad={"t": 50},
steps=steps
)]
fig.update_layout(
sliders=sliders
)
fig.update_layout(height=600, xaxis_rangeslider_visible=False)
fig.show()
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)
image of plotly chart
Hello, I'm really struggling to figure out how to format the axes on this chart. I've gone through the documentation and tried all sorts of different formatting suggestions from here and elsewhere but really not getting it. As you can see, the bottom chart has a .5 number, I want that to be skipped altogether and only have whole numbers along the axis.
I've seen ,d as a tickformat option to do this in about every answer, but I can't get that to work or I'm not seeing how to apply it to the second chart.
Can anyone with some Plotly charting experience help me out?
Here's the pertinent code:
def create_chart():
#Put data together into an interactive chart
fig.update_layout(height=500, width=800, yaxis_tickprefix = '$', hovermode='x unified', xaxis_tickformat =',d',
template=symbol_template, separators=".", title_text=(df.columns[DATA_COL_1]) + " & Units 2015-2019"
)
I believe what is happening is that the xaxis_tickformat parameter is affecting only the first subplot, but not the second one. To modify the formatting for each subplot, you can pass a dictionary with the tickformat parameter to yaxis, yaxis2, .... and so on for however many subplots you have (in your case, you only have 2 subplots).
import pandas as pd
from plotly.subplots import make_subplots
import plotly.graph_objects as go
## recreate the df
df = pd.DataFrame({'Year':[2015,2016,2017,2018,2019],
'Sales':[8.8*10**7,8.2*10**7,8.5*10**7,9.1*10**7,9.6*10**7],
'Units':[36200,36500,36900,37300,37700]})
def create_chart():
#Put data together into an interactive chart
fig = make_subplots(rows=2, cols=1)
fig.add_trace(go.Scatter(
x=df.Year,
y=df.Sales,
name='Sales',
mode='lines+markers'
), row=1, col=1)
fig.add_trace(go.Scatter(
x=df.Year,
y=df.Units,
name='Units',
mode='lines+markers'
), row=2, col=1)
fig.update_layout(
title_x=0.5,
height=500,
width=800,
yaxis_tickprefix = '$',
hovermode='x unified',
xaxis_tickformat =',d',
## this will change the formatting for BOTH subplots
yaxis=dict(tickformat ='d'),
yaxis2=dict(tickformat ='d'),
# template=symbol_template,
separators=".",
title={
'text':"MCD Sales & Units 2015-2019",
'x':0.5
}
)
fig.show()
create_chart()
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!
Say I have the following figure:
import numpy as np
import plotly.graph_objs as go
z=np.random.randint(1000, 11000, size=20)
trace=dict(type='scatter',
x=3+np.random.rand(20),
y=-2+3*np.random.rand(20),
mode='markers',
marker=dict(color= z,
colorscale='RdBu', size=14, colorbar=dict(thickness=20)))
axis_style=dict(zeroline=False, showline=True, mirror=True)
layout=dict(width=550, height=500,
xaxis=axis_style,
yaxis=axis_style,
hovermode='closest',
)
fig=go.FigureWidget(data=[trace], layout=layout)
fig
Now say I want the colorbar to have a title. Since plotly does not currently have a direct way to do that, if I understand correctly, I am doing this through annotations as shown here:
layout.update(
annotations=[dict(
x=1.12,
y=1.05,
align="right",
valign="top",
text='Colorbar Title',
showarrow=False,
xref="paper",
yref="paper",
xanchor="center",
yanchor="top"
)
]
)
As we can see, the colorbar title appears:
fig=go.FigureWidget(data=[trace], layout=layout)
fig
However, now say I want to place the colorbar title sideways, along the colorbar, like so:
How do I do this?
Parameter textangle do it for you. Example from plotly docs. Setting textangle=-90 rotate annotation how you want.
Code:
# import necessaries libraries
import numpy as np
import plotly.offline as py
import plotly.graph_objs as go
z = np.random.randint(1000, 11000, size=20)
# Create a trace
trace = dict(type='scatter',
x=3+np.random.rand(20),
y=-2+3*np.random.rand(20),
mode='markers',
marker=dict(color=z, colorscale='RdBu',
size=14, colorbar=dict(thickness=20)))
# Define axis_style
axis_style = dict(zeroline=False, showline=True, mirror=True)
# Specify layout style
layout = dict(width=550, height=500,
xaxis=axis_style,
yaxis=axis_style,
hovermode='closest',
)
# Update layout with annotation
layout.update(
annotations=[dict(
# Don't specify y position,because yanchor="middle" do it for you
x=1.22,
align="right",
valign="top",
text='Colorbar Title',
showarrow=False,
xref="paper",
yref="paper",
xanchor="right",
yanchor="middle",
# Parameter textangle allow you to rotate annotation how you want
textangle=-90
)
]
)
# Create FigureWidget
fig = go.FigureWidget(data=[trace], layout=layout)
# Plot fig
py.plot(fig)
Output:
For anyone who may have found this question now, there is (now?) a very easy way of adding a title to a colorbar, and to make it oriented sideways along the colorbar using the colorbar title property.
In this case, we could just update trace like so:
# Create a trace
trace = dict(type='scatter',
x=3+np.random.rand(20),
y=-2+3*np.random.rand(20),
mode='markers',
marker=dict(color=z, colorscale='RdBu', size=14,
colorbar=dict(thickness=20,
title=dict(text="Colorbar title", orient="right"))))
Documentation here: https://plotly.com/python/reference/scatter/#scatter-marker-colorbar