Plotly: How to save interactive plotly plot as pdf file? - python

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!

Related

Change color of candle stick graph in python Plotly

I have a candle stick graph created to show monthly candles of a stock using plotly in python. I want to customize only one candle for April 2022 (see figure). Here is the complete code.
fig = make_subplots(rows=1, cols=1, subplot_titles=[], \
specs=[[{"secondary_y": True}]], \
vertical_spacing=0, shared_xaxes=True, row_width=[1.0])
fig.add_trace(go.Scatter(x=df.index, y=df['Pivot'], marker=dict(color='black'), line=dict( width=2),
mode='lines', name='Pivot Point'), row=1, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df['R1'], marker=dict(color='olive'), line=dict( width=1,dash='dot'),
mode='lines', name='Resistance 1'), row=1, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df['S1'], marker=dict(color='turquoise'), line=dict( width=2,dash='dot'),
mode='lines', name='Support 1'), row=1, col=1)
# Adding Candlestick graph
fig.add_trace(go.Candlestick(x=df.index,
open=df['Open'],
close=df['Close'],
low=df['Low'],
high=df['High'],
increasing_line_color='green', decreasing_line_color='red', name='HRC Price'),row=1, col=1,)
fig.update_layout(
title='HRC Monthly Price',
yaxis_title='Price',
shapes = [dict(
x0='2022-03-14', x1='2022-03-14', y0=0, y1=1, xref='x', yref='paper',
line_width=2)],
annotations=[dict(
x='2022-03-14', y=0.05, xref='x', yref='paper',
showarrow=False, xanchor='left', text='Ukraine - Russia War Starts')]
)
return fig
Output Graph
How do i color the last candle with a different color?
You can split your df into two separate dataframes called df_before and df_last using iloc:
df_before = df.iloc[:len(df)-1]
df_last = df.iloc[len(df)-1:]
Then plot these in separate traces and specify the desired color for the last candle:
# Adding Candlestick graph
fig.add_trace(go.Candlestick(x=df_before.index,
open=df_before['Open'],
close=df_before['Close'],
low=df_before['Low'],
high=df_before['High'],
increasing_line_color='green', decreasing_line_color='red', name='HRC Price'),row=1, col=1,)
fig.add_trace(go.Candlestick(x=df_last.index,
open=df_last['Open'],
close=df_last['Close'],
low=df_last['Low'],
high=df_last['High'],
increasing_line_color='purple', decreasing_line_color='blue', name='HRC Price'),row=1, col=1,)
Using some sample data, I get the following result:

in plotly show text by default for map when saving to image

I have created a plotly map and added some lat, lon points on it with marker and text and it shows fine when viewed as interactive map on Jupyter notebook but when I'm saving that map as PNG text doesn't show.
here is my code
import plotly.graph_objects as go
mapbox_access_token = open(".mapbox_token").read()
fig = go.Figure(go.Scattermapbox(
lat=['45.5017'],
lon=['-73.5673'],
mode='markers',
marker=go.scattermapbox.Marker(
size=14
),
text=['Montreal'],
))
fig.update_layout(
hovermode='closest',
mapbox=dict(
accesstoken=mapbox_access_token,
bearing=0,
center=go.layout.mapbox.Center(
lat=45,
lon=-73
),
pitch=0,
zoom=5
)
)
fig.show()
Expected output
Output I get when image is saved
i just want all text/annotation visible after saving image
The hover function can be enabled by moving the mouse cursor closer. So if you want to save a graph, that information will not be saved. If you add text information to the map as annotations, it will be saved in the image. The position, text color, font family, and size are specified for the annotation. The display format can be standardized by using texttemplate.
import plotly.graph_objects as go
mapbox_access_token = open("mapbox_api_key.txt").read()
fig = go.Figure(go.Scattermapbox(
lat=['45.5017'],
lon=['-73.5673'],
mode='markers+text',
marker=go.scattermapbox.Marker(
size=14
),
text=['Montreal'],
textfont={'color':'royalblue', 'family':'Arial','size':16},
textposition='bottom right',
texttemplate='(%{lat},%{lon})%{text}'
))
fig.update_layout(
hovermode='closest',
mapbox=dict(
accesstoken=mapbox_access_token,
bearing=0,
center=go.layout.mapbox.Center(
lat=45,
lon=-73
),
pitch=0,
zoom=5
)
)
fig.show()

Convert plotly marker from continuous to discrete

Following is my input file i'm trying to display on a map using plotly.
data.csv
lat,long,type
-7.80715,110.371203,1
-7.791087,110.368346,3
-7.778744,110.365107,7
-7.77877,110.365379,4
The script works but the scale is displayed in a continuous format. I tried to convert the column type to text as mentioned here but I couldn't get it to work. Is there a easier way to fix this problem?
df = pd.read_csv("data.csv").dropna()
fig = go.Figure(go.Scattermapbox(
lat=df["lat"].tolist(),
lon=df["long"].tolist(),
mode='markers',
text=df['type'].tolist(),
marker=go.scattermapbox.Marker(
size=10,
color=df['type'],
showscale=True
),
))
fig.show()
If you want to specify a discrete color, you can either deal with it directly as a list of color specifications, or you can specify the default color name in plotly_express.
import plotly.graph_objects as go
import plotly.express as px
mapbox_access_token = open("mapbox_api_key.txt").read()
colors = px.colors.qualitative.D3
fig = go.Figure(go.Scattermapbox(
lat=df["lat"].tolist(),
lon=df["long"].tolist(),
mode='markers',
text=df['type'].tolist(),
marker=go.scattermapbox.Marker(
size=10,
color=colors,
showscale=False
),
))
fig.update_layout(
autosize=False,
height=450,
width=1000,
mapbox=dict(
accesstoken=mapbox_access_token,
style="outdoors",
center=dict(
lat=-7.78,
lon=110.365
),
zoom=10),
showlegend = False
)
fig.show()

How to add caption & subtitle using plotly method in python

I'm trying to plot a bar chart using plotly and I wanted to add a caption and subtitle.(Here you can take any example of your choice to add caption and subtitle)
My code for plotting the bar chart:
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Bar(x=["Apple", 'Mango', 'Banana'], y=[400, 300, 500]))
fig.show()
Plotly takes your string and passes it as HTML. Adding HTML in the title string or X axis string lets you put in some quick subtitles/captions in both ploty graph objects and plotly express.
<br> is a line break, and <sup> is superscript, which lets you quickly make a smaller subtitle or caption.
graph objects:
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Bar(x=["Apple", 'Mango', 'Banana'], y=[400, 300, 500]))
fig.update_layout(
title=go.layout.Title(
text="Plot Title <br><sup>Plot Subtitle</sup>",
xref="paper",
x=0
),
xaxis=go.layout.XAxis(
title=go.layout.xaxis.Title(
text="Fruits<br><sup>Fruit sales in the month of January</sup>"
)
)
)
fig.show()
plotly express:
import plotly.express as px
fig = px.bar(
x=["Apple", 'Mango', 'Banana'],
y=[400, 300, 500],
title = "Plot Title <br><sup>Plot Subtitle</sup>",
labels = {'x':"Fruits<br><sup>Fruit sales in the month of January</sup>",
'y':'count'}
)
fig.show()
figure:
Use fig.update_layout(title_text='Your title') for your caption. There's no built-in option for subtitles. But you can get the desired effect by moving the x-axis labels to the top and at the same time insert an annotation at the bottom right. I've tried with other y-values as well, but there doesn't seem to be a way to get the annotations outside the plot itself. You could also change the fonts of the caption and subtitle to make them stand out from the rest of the labels.
Plot:
Code:
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Bar(x=["Apple", 'Mango', 'Banana'], y=[400, 300, 500]))
fig.update_layout(title=go.layout.Title(text="Caption", font=dict(
family="Courier New, monospace",
size=22,
color="#0000FF"
)))
fig.update_layout(annotations=[
go.layout.Annotation(
showarrow=False,
text='Subtitle',
xanchor='right',
x=1,
xshift=275,
yanchor='top',
y=0.05,
font=dict(
family="Courier New, monospace",
size=22,
color="#0000FF"
)
)])
fig['layout']['xaxis'].update(side='top')
fig.show()
Maybe something like this?
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Bar(x=["Apple", 'Mango', 'Banana'], y=[400, 300, 500]))
fig.update_layout(
title=go.layout.Title(
text="Plot Title",
xref="paper",
x=0
),
xaxis=go.layout.XAxis(
title=go.layout.xaxis.Title(
text="x Axis",
font=dict(
family="Courier New, monospace",
size=18,
color="#7f7f7f"
)
)
),
yaxis=go.layout.YAxis(
title=go.layout.yaxis.Title(
text="y Axis",
font=dict(
family="Courier New, monospace",
size=18,
color="#7f7f7f"
)
)
)
)
fig.show()

Can't add time to my X axis on my Plotly chart

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)

Categories