Missing title displayed in plotly - python

I am trying to change the background color in plotly, but after using layout function, I'm missing title from plotly.
layout = Layout(
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)'
)
data['Country'].value_counts()[:10][::-1].iplot(kind="barh",bargap=.5, title="Top 10 countries faced terrorist attacks", colors="#182844", layout=layout)

You'll be better off using go.Figure() instead of iplot(). It's hard to make out what the problem is with your plot, but with an example from plot.ly/python/horizontal-bar-charts/ you can easily set both title and background color using fig.update_layout()
Plot:
Code:
import plotly.graph_objects as go
fig = go.Figure(go.Bar(
x=[20, 14, 23],
y=['giraffes', 'orangutans', 'monkeys'],
orientation='h'))
fig.update_layout(title='Title',
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)')
fig.show()

I tried adding layout the the iplot itself and it worked. We can also adjust margin along with it.
Sample Code:
data['Nationality'].value_counts()[0:10][::-1].iplot(kind="barh",bargap=.5,
colors="mediumorchid", layout=Layout(paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
width=800, height=500,
title='Nationality of terrorist attacks',
margin=dict(l=200, r=50, t=80, b=50)))
enter image description here

Related

Plotly two mapbox figures in a single map with different color

I want to plot two mapbox figures in a single map. This is what I have right now:
fig = px.choropleth_mapbox(geo_df,
geojson=geo_df.geometry,
locations=geo_df.index,
color="TOTAL_POPULATION", color_continuous_scale=px.colors.sequential.Greens,
center={"lat": 40.7, "lon": -73.95},
mapbox_style="open-street-map",
zoom=10)
fig2 = px.scatter_mapbox(geo_df, lat="INTPTLAT", lon="INTPTLON",
size="MEDIAN_VALUE", color="MEDIAN_VALUE",
color_continuous_scale=px.colors.sequential.Blues,
mapbox_style="open-street-map")
fig.add_trace(fig2.data[0])
fig.update_layout(
autosize=False,
width=1400,
height=1000,
)
Here, I have specified different colors for the two mapbox, but its only picking the first one and applying it to both. How can I print them with different colors to improve visibility?
Since your question does not present any data, I have combined the reference example with another example to confirm the events.
I searched the plotly community for a solution and identified examples that would solve the issue.
The way to do this is to add a graph object choropleth map to the graph object and then add an express graph.
One issue is that the specified colormap is not valid. We are currently investigating but may not be able to reach a solution. I believe it is compatible with the solution to your question.
import plotly.express as px
import plotly.graph_objects as go
px.set_mapbox_access_token(open("mapbox_api_key.txt").read())
# fig for data
df_election = px.data.election()
geojson = px.data.election_geojson()
# fig2 for data
df_car = px.data.carshare()
df_car['peak_hour2'] = df_car['peak_hour']*20
fig = go.Figure()
fig.add_trace(go.Choroplethmapbox(geojson=geojson,
z=df_election["Bergeron"],
colorscale='greens',
locations=df_election["district"],
featureidkey="properties.district",
colorbar_x=1.12,
colorbar_title='election'
))
fig.update_layout(mapbox_style="open-street-map",
mapbox_center={"lat": 45.5517, "lon": -73.7073},
mapbox_zoom=10)
map_scatter = px.scatter_mapbox(df_car,
lat="centroid_lat",
lon="centroid_lon",
color="peak_hour",
size="car_hours",
color_continuous_scale=px.colors.sequential.Blues,
size_max=15,
zoom=9)
fig.add_traces(list(map_scatter.select_traces()))
fig.update_layout(coloraxis={'colorbar': {'title': {'text': 'peak_hour'}}})
fig.update_layout(autosize=True, height=600, margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

Scroll between multiple subplots

i have a question regarding subplots.
i’m creating plots using this command:
figure = make_subplots(
rows=4,
cols=1,
shared_xaxes=True,
subplot_titles=("title1", "title2", "title3", "title4"),
vertical_spacing=0.1,
column_titles=[
f'title'
]
)
# then creating multiple candlestick graphs like this for each row:
figure.add_trace(
go.Candlestick(
x=inner_data.index,
open=inner_data['open'],
high=inner_data['high'],
low=inner_data['low'],
close=inner_data['close'],
name=f"{ticker} - INNER GRAPH"
),
row=row,
col=1
)
figure.show()
but because i have too many rows, the plots are shrinking a lot, and i cannot see anything.
is there a way to keep the size big, and create a scroll option in the page that opens up? i have not found it anywhere in the documentation…
thanks in advance,
Yaniv
A candlestick graph has been created using four stock prices. The display area can be changed by setting the graph height. The unit is pixels. Also, the range slider is not shown as an element that makes the graph area narrower. If necessary, change it to True. Since column titles and sub-titles are covered, the column titles are not set, but are changed to the overall title.
import yfinance as yf
tickers = "AAPL TSLA GOOG NFLX"
df = yf.download(tickers, start="2021-07-01", end="2022-07-01", group_by='ticker')
df = df.stack(0).reset_index().rename(columns={'level_1':'Ticker'})
from plotly.subplots import make_subplots
import plotly.graph_objects as go
figure = make_subplots(
rows=4,
cols=1,
shared_xaxes=True,
subplot_titles=tickers.split(' '),
vertical_spacing=0.1,
# column_titles=[
# f'title'
# ]
)
for row,ticker in enumerate(tickers.split(' ')):
inner_data = df[df['Ticker'] == ticker]
figure.add_trace(
go.Candlestick(
x=inner_data.index,
open=inner_data['Open'],
high=inner_data['High'],
low=inner_data['Low'],
close=inner_data['Close'],
name=f"{ticker} - INNER GRAPH"
), row=row+1, col=1
)
figure.update_layout(title='title',
autosize=True,
height=800,
)
figure.update_xaxes(rangeslider=dict(visible=False))
figure.show()

How to add an extra point over a boxplot graph with plotly?

I am trying to overlay a point over a boxplot with Plotly and Python. I am able to add two traces to the same graph, but I couldn't find a way to make the extra point closer to the boxplot.
This is the image I get:
and the code that generates it is:
x = np.fromiter(duplicates.values(), dtype=float)
fig = go.Figure()
fig.update_layout(autosize=False, width=400, height=150, paper_bgcolor="White", plot_bgcolor='rgba(0,0,0,0)',
hovermode=False, margin=dict(l=10, r=10, b=10, t=10, pad=4),
boxmode='group', boxgroupgap=0.25,
boxgap=0.25,
)
fig.add_trace(go.Box(x=x, showlegend=False))
fig.add_trace(go.Scatter(x=np.array(duplicates[sample_id]), y=np.array(0), mode='markers', showlegend=False))
fig.update_xaxes(title='')
fig.update_yaxes(showticklabels=False)
my_div = plotly.offline.plot(fig, output_type='div',
show_link=False,
config=dict(
displayModeBar=False
))

Plotly: How to only show vertical and horizontal line (crosshair) as hoverinfo?

I want to plot a chart with two subplots in plotly dash. My entire chart looks like this:
import pandas as pd
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from plotly.subplots import make_subplots
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv').iloc[:60]
fig = make_subplots(rows=2, cols=1, row_heights=[0.8, 0.2], vertical_spacing=0)
fig.add_trace(go.Candlestick(open=df['AAPL.Open'], high=df['AAPL.High'], low=df['AAPL.Low'], close=df['AAPL.Close'],
increasing_line_color='#0384fc', decreasing_line_color='#e8482c', name='AAPL'), row=1, col=1)
fig.add_trace(go.Scatter(y=np.random.randint(20, 40, len(df)), marker_color='#fae823', name='VO', hovertemplate=[]), row=2, col=1)
fig.update_layout({'plot_bgcolor': "#21201f", 'paper_bgcolor': "#21201f", 'legend_orientation': "h"},
legend=dict(y=1, x=0),
font=dict(color='#dedddc'), dragmode='pan', hovermode='x unified',
margin=dict(b=20, t=0, l=0, r=40))
fig.update_xaxes(showgrid=False, zeroline=False, rangeslider_visible=False, showticklabels=False,
showspikes=True, spikemode='across', spikesnap='data', showline=False, spikedash='solid')
fig.update_yaxes(showgrid=False, zeroline=False)
fig.update_traces(xaxis='x', hoverinfo='none')
app = dash.Dash(__name__)
app.layout = html.Div(children=[
html.Div(dcc.Graph(id='chart', figure=fig, config={'displayModeBar': False}))])
if __name__ == '__main__':
app.run_server(debug=True, dev_tools_ui=False, dev_tools_props_check=False)
What I need is a so called crosshair that is common in trading charts. Basically it consists of two lines that are connected to x and y axes and moves with cursor. This is a screenshot from tradingview.com charts:
However in my chart there is a little icon that appears when the cursor is on candlesticks:
What I have found out so far is that when the cursor is on the scatter plot, the icon disappears and it works fine. I think that is because I set hovertemplate=[] in the scatterplot. I cannot do that in the candlestick plot because there is no such parameter for it. Moreover, this icon only appears if I set hovermode='x unified'. If I set it to x, the little icon doesn't appear. But I need it to be exactly like the tradingview.com example that I showed.
Is there any way to replicate that crosshair?
UPDATE 1:
I tried fig.update_layout(hoverdistance=0). But the problem is that when the cursor is not on the candlesticks, the crosshair is just not right. I took two screenshots: the first one is from tradingview.com charts and the second one is from my code with hoverdistance set to 0.
As can be seen, when the cursor is not on the candlesticks, in the first screenshot the crosshair is still correct. However, in the second screenshot it is just not working correctly. It only works if the cursor is on the candlesticks ONLY.
I just want to copy tradingview.com crosshair. Nothing less and nothing more.
UPDATE 2:
I think the answer could be on these plotly docs. I am working on it currently. Please share your comments about this update.
This should do it:
fig.update_layout(hoverdistance=0)
And setting spikesnap='cursor' for xaxes and yaxes.
These little adjustments will keep the crosshair intact and remove the little icon that has been bothering you.
From the docs:
Plot:
hoverdistance
Sets the default distance (in pixels) to look for data
to add hover labels (-1 means no cutoff, 0 means no looking for data).
This is only a real distance for hovering on point-like objects, like
scatter points. For area-like objects (bars, scatter fills, etc)
hovering is on inside the area and off outside, but these objects will
not supersede hover on point-like objects in case of conflict.
Complete code: (but with no dash elements)
import pandas as pd
import numpy as np
import plotly.graph_objs as go
from plotly.subplots import make_subplots
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv').iloc[:60]
fig = make_subplots(rows=2, cols=1, row_heights=[0.8, 0.2], vertical_spacing=0)
fig.add_trace(go.Candlestick(open=df['AAPL.Open'], high=df['AAPL.High'], low=df['AAPL.Low'], close=df['AAPL.Close'],
increasing_line_color='#0384fc', decreasing_line_color='#e8482c', name='AAPL'), row=1, col=1)
fig.add_trace(go.Scatter(y=np.random.randint(20, 40, len(df)), marker_color='#fae823', name='VO', hovertemplate=[]), row=2, col=1)
fig.update_layout({'plot_bgcolor': "#21201f", 'paper_bgcolor': "#21201f", 'legend_orientation': "h"},
legend=dict(y=1, x=0),
font=dict(color='#dedddc'), dragmode='pan', hovermode='x unified',
margin=dict(b=20, t=0, l=0, r=40))
fig.update_yaxes(showgrid=False, zeroline=False, showticklabels=False,
showspikes=True, spikemode='across', spikesnap='cursor', showline=False, spikedash='solid')
fig.update_xaxes(showgrid=False, zeroline=False, rangeslider_visible=False, showticklabels=False,
showspikes=True, spikemode='across', spikesnap='cursor', showline=False, spikedash='solid')
fig.update_layout(hoverdistance=0)
fig.update_traces(xaxis='x', hoverinfo='none')
fig.show()
If you set hovermode='x' then you can format the style of the spike line like this:
fig.update_xaxes(spikecolor="grey",spikethickness=1)
UPDATE:
spikesnap='cursor' will get you closer, but not working exactly for the candlestick.
fig.update_xaxes(showgrid=False, zeroline=False, rangeslider_visible=False, showticklabels=False,
showspikes=True, spikemode='across', spikesnap='cursor', showline=False,
spikecolor="grey",spikethickness=1, spikedash='solid')
fig.update_yaxes(showspikes=True, spikedash='solid',spikemode='across',
spikecolor="grey",spikesnap="cursor",spikethickness=1)
fig.update_layout(spikedistance=1000,hoverdistance=1000)
All the man too complex, the easiest way:
fig.update_layout(hovermode='x unified')
Docs for hovermode is here and python reference here

Modify axes range using plotly

I'm using the following code to generate a bubble plot using plotly:
Dataframe.iplot(kind='bubble', x='branch', y='retention', size='active_users', text='active_users',
xTitle='', yTitle='Retention',
filename='cufflinks/PlotName')
I'd like to set a manual range for Y axis.
Any help would be appreciated.
A solution that works with subplots is:
fig.update_yaxes(range=[0, 0.4], row=1, col=1)
import plotly.graph_objs as go
layout = go.Layout(
yaxis=dict(
range=[0, 0.4]
)
)
Dataframe.iplot(kind='bubble', x='branch', y='retention', size='active_users', text='active_users',
xTitle='', yTitle='Retention',
filename='cufflinks/PlotName', layout = layout)
This will do the trick.

Categories