I'm creating a Dash webapp where i have a real-time plotly chart. This chart gets updated every second. I would like to add to my X axis time instead of a fixed value. I tried setting tickvals= to dt.now but it doesn't work, since tickvals needs an array. Any advice?
def gen_wind_speed(interval):
trace = Scatter(
y=df['num'],
line=Line(
color='#42C4F7'
),
)
layout = Layout(
height=450,
xaxis=dict(
showgrid=False,
showline=False,
zeroline=False,
fixedrange=True,
tickvals= dt.now
),
margin=Margin(
t=45,
l=50,
r=50
)
)
return Figure(data=[trace], layout=layout)
Related
I would like to create a plotly plot where I can change the value of the plotly express color argument via a button. I am using plotly.express.scatter for this.
For example, the initial plot shown is px.scatter(df, "sepal_length", "sepal_width", color="species"). Changing from "species" to "petal length" in a dropdown menu would update the plot so that instead color="petal_length". If it makes a difference, "species" uses the default discrete color sequence while "petal_length" uses the default continuous color scale.
The code I have so far makes the initial plot and dropdown buttons, but choosing the buttons has no effect. I don't understand how to get the plotly express color argument passed through this Plotly.update interface.
import plotly.express as px
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
fig = px.scatter(df, "sepal_length", "sepal_width", color="species")
fig.update_layout(
updatemenus=[
dict(
buttons=list([
dict(
args=["color", "species"],
label="species",
method="update"
),
dict(
args=["color", "petal_length"],
label="petal length",
method="update"
),
]),
showactive=True,
x=0.05,
xanchor="left",
y=1.06,
yanchor="top"
),
]
)
fig.update_layout(
annotations=[
dict(text="color", x=0.015, xref="paper", y=1.05, yref="paper",
align="left", showarrow=False),
])
fig.show()
For color='species', three graphs are internally created for each categorical variable. And color='petal_length' consists of a single graph data. So, it is possible to handle this by setting the drop-down to show/hide the graph. The actual code reuses the data created by express.scatter. The data for each graph will be configured in a graph object; three will be shown and one will be hidden. Set the button to restyle as a function of the button.
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
fig1 = px.scatter(df, "sepal_length", "sepal_width", color="species")
fig2 = px.scatter(df, "sepal_length", "sepal_width", color="petal_length")
fig = go.Figure()
fig.add_trace(go.Scatter(fig1.data[0], visible=True))
fig.add_trace(go.Scatter(fig1.data[1], visible=True))
fig.add_trace(go.Scatter(fig1.data[2], visible=True))
fig.add_trace(go.Scatter(fig2.data[0], visible=False))
fig.update_layout(
updatemenus=[
dict(
buttons=list([
dict(
args=["visible", [True,True,True,False]],
label="species",
method="restyle"
),
dict(
args=["visible", [False,False,False,True]],
label="petal length",
method="restyle"
),
]),
showactive=True,
x=0.05,
xanchor="left",
y=1.2,
yanchor="top"
),
]
)
fig.update_layout(
annotations=[
dict(text="color", x=0.01, xref="paper", y=1.16, yref="paper",
align="left", showarrow=False),
])
fig.update_layout(xaxis_title_text='sepal_length', yaxis_title_text='sepal_width', legend_title_text='species')
fig.show()
I created an interactive plot using plotly as following:
tracer_red = go.Scatter(x=Xedges_red, y=Yedges_red,
mode='lines',
line= dict(color="#FA0000", width=1),
hoverinfo='none',
showlegend=False)
# positive:
tracer_green = go.Scatter(x=Xedges_green, y=Yedges_green,
mode='lines',
line= dict(color= "#29A401", width=1),
hoverinfo='none',
showlegend=False)
# nodes
tracer_marker = go.Scatter(x=Xnodes, y=Ynodes,
mode='markers+text',
textposition='middle center',
marker=dict(size=node_size,
line=dict(width=0.8, color='black'),
color=node_colour, symbol=node_shape),
hovertext=description,
hoverinfo='text',
text=node_label,
textfont=dict(size=10),
showlegend=False)
axis_style = dict(title='',
titlefont=dict(size=20),
showgrid=False,
zeroline=False,
showline=False,
ticks='',
showticklabels=False)
layout = dict(title='',
width=1300,
height=900,
autosize=False,
showlegend=False,
xaxis=axis_style,
yaxis=axis_style,
hovermode='closest',
plot_bgcolor = '#fff')
fig = dict(data=[tracer_red, tracer_green, tracer_marker], layout=layout)
display(HTML("""<p>Node sizes are proportional to the size of annualised returns.<br>
Node colours signify positive or negative returns since beginning of the timeframe.</p> """))
plot(fig)
I want to save the plot as a pdf file or as a picture.
when I saveing with the "camera" it saveing in a very low resulotion
because I created the fig as a dict, I cant us the command fig.write_image()
do you know other way to save the fig as a pic\PDF file?
Thank you!
I am plotting a graph with plotly on jupyter notebook.
The actual graph should look like this.
However, I am getting this.
Please how can i correct this.
Please see below code:
# Setting layout for our plot
layout = go.Layout(
title='Stock Prices of Tesla',
xaxis=dict(
title='Date',
titlefont=dict(
family='Courier New, monospace',
size=18,
color='#7f7f7f'
)
),
yaxis=dict(
title='Price',
titlefont=dict(
family='Courier New, monospace',
size=18,
color='#7f7f7f'
)
)
)
tesla_data = [{'x': tesla['Date'], 'y': tesla['Close']}]
plot = go.Figure(data=tesla_data, layout=layout)
#plot(plot) #plotting offline
iplot(plot)
Please see snapshot of my data
I am using python libraries called dash and plotly to create an interactive dashboard. I would like to set the map size to let it fill the whole Div. The map is created using mapbox. I tried to set style but not working.
My map looks like this:
I noticed other people’s map fill the whole Div. (See the position of widgets):
Here are my code:
map_data = [
go.Scattermapbox(
lat=df['latitude'],
lon=df['longitude'],
mode='markers',
marker=dict(
cmax=50,
cmin=0,
color=df['depth'],
colorbar=dict(
title='Colorbar'
),
colorscale='YlGnBu',
reversescale=True,
size=5,
# opacity=0.9
),
text=df['depth'],
hoverinfo='text'
)
]
map_layout = go.Layout(
title='Bathymetrical Data',
autosize=True,
hovermode='closest',
xaxis=dict(hoverformat='.5f'),
yaxis=dict(hoverformat='.5f'),
mapbox=dict(
accesstoken=mapbox_access_token,
bearing=0,
center=dict(
lat=lat,
lon=lon
),
pitch=0,
zoom=10,
),
)
figure = {
'data': map_data,
'layout': map_layout
}
Dose anyone know how I can change my code to make my map looks like that?
I think what you're after is layout margins:
map_layout = go.Layout(
title='Bathymetrical Data',
autosize=True,
hovermode='closest',
margin=dict(t=0, b=0, l=0, r=0),
...
note that these margins affect the "inside" of the chart, you can also set the width and height parameters in the layout to change the size of the whole figure. For the width I strongly recommend using the css' grid on this css made for dash.
I am using Plotly API to draw line charts from a dataset in python. For example I have this dataset from the year 2018.
Now I want to check weather the weekend days have higher demand in contrast to the weekdays. My goal is to mark the lines in the diagram for saturday and sunday.
Does Plotly provide methods to do this? If not, is there any easy method to achieve this?
You can make a marker plot and then overlay a line plot to get the desired output where the marker plot must be passed with a list of colors that is made based on the condition.
To get a clear picture see the below codes,
# make a dummy time data
x_values = pd.date_range(start=pd.Timestamp('2018-01-01'), end=pd.Timestamp('2019-01-01'), freq='1 D')
# making a random time series
y_values = np.random.randn(len(x_values))
# making color list
# red if the day is saturday or sunday else green
colors = ['red' if int(pd.Timestamp(d).weekday()) >= 5 else 'green' for d in x_values]
# make the plot
trace_0 = go.Scatter(
x=x_values,
y=y_values,
mode='markers',
marker=dict(
color = colors
)
)
trace_1 = go.Scatter(
x=x_values,
y=y_values,
mode='lines',
marker=dict(
color = 'black'
)
)
layout = dict(
title='Time Series with Rangeslider',
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1,
label='1m',
step='month',
stepmode='backward'),
dict(count=6,
label='6m',
step='month',
stepmode='backward'),
dict(step='all')
])
),
rangeslider=dict(
visible = True
),
type='date'
)
)
fig = {
'data': [trace_0, trace_1],
'layout': layout,
}
py.iplot(fig, filename='Plot')
Output plot
I have also implemented a range slider, if that is not needed edit it out from the layout.