I am building a dashboard using Potly Dashboard. I am using a dark bootstrap theme therefore I don't want a white background.
However, my map now looks like this:
And the code that produced it is shown below:
trace_map = html.Div(
[
dcc.Graph(
id = "map",
figure = go.Figure(
data=go.Choropleth(
locations=code, # Spatial coordinates
z = df.groupby(['month']).sum()['Sales'].astype(int),
locationmode = 'USA-states',
colorscale = 'Reds',
colorbar_title = "USD",
), layout = go.Layout(title = 'The Cities Sold the Most Product',
font = {"size": 9, "color":"White"},
titlefont = {"size": 15, "color":"White"},
geo_scope='usa',
margin={"r":0,"t":40,"l":0,"b":0},
paper_bgcolor='#4E5D6C',
plot_bgcolor='#4E5D6C',
)
)
)
]
)
I have tried paper_bgcolor, and plot_bgcolor but couldn't make it work.
Ideally I would like to achieve how this image looks (please ignore the red dots):
Generally:
fig.update_layout(geo=dict(bgcolor= 'rgba(0,0,0,0)'))
And in your specific example:
go.Layout(geo=dict(bgcolor= 'rgba(0,0,0,0)')
Plot:
Code:
import plotly.graph_objects as go
fig = go.Figure(
data=go.Choropleth(
#locations=code, # Spatial coordinates
#z = df.groupby(['month']).sum()['Sales'].astype(int),
locationmode = 'USA-states',
colorscale = 'Reds',
colorbar_title = "USD",
), layout = go.Layout(geo=dict(bgcolor= 'rgba(0,0,0,0)'),
title = 'The Cities Sold the Most Product',
font = {"size": 9, "color":"White"},
titlefont = {"size": 15, "color":"White"},
geo_scope='usa',
margin={"r":0,"t":40,"l":0,"b":0},
paper_bgcolor='#4E5D6C',
plot_bgcolor='#4E5D6C',
)
)
fig.show()
And you might want to change the color of the lakes too. But do note that setting lakecolor = 'rgba(0,0,0,0)' will give the lakes the same color as the states and not the bakground. So I'd go with lakecolor='#4E5D6C'. You could of course do the same thing with bgcolor, but setting it to 'rgba(0,0,0,0)' gets rid of the white color which you specifically asked for.
Lake color plot:
Lake color code:
import plotly.graph_objects as go
fig = go.Figure(
data=go.Choropleth(
#locations=code, # Spatial coordinates
#z = df.groupby(['month']).sum()['Sales'].astype(int),
locationmode = 'USA-states',
colorscale = 'Reds',
colorbar_title = "USD",
), layout = go.Layout(geo=dict(bgcolor= 'rgba(0,0,0,0)', lakecolor='#4E5D6C'),
title = 'The Cities Sold the Most Product',
font = {"size": 9, "color":"White"},
titlefont = {"size": 15, "color":"White"},
geo_scope='usa',
margin={"r":0,"t":40,"l":0,"b":0},
paper_bgcolor='#4E5D6C',
plot_bgcolor='#4E5D6C',
)
)
fig.show()
And we could just as well change the state border colors, or what is more cryptically known as subunitcolor in this context. And to better match your desired endresult we could spice up the landcolor as well:
State border and state colors, plot:
State border and state colors, code:
import plotly.graph_objects as go
fig = go.Figure(
data=go.Choropleth(
#locations=code, # Spatial coordinates
#z = df.groupby(['month']).sum()['Sales'].astype(int),
locationmode = 'USA-states',
colorscale = 'Reds',
colorbar_title = "USD",
), layout = go.Layout(geo=dict(bgcolor= 'rgba(0,0,0,0)', lakecolor='#4E5D6C',
landcolor='rgba(51,17,0,0.2)',
subunitcolor='grey'),
title = 'The Cities Sold the Most Product',
font = {"size": 9, "color":"White"},
titlefont = {"size": 15, "color":"White"},
geo_scope='usa',
margin={"r":0,"t":40,"l":0,"b":0},
paper_bgcolor='#4E5D6C',
plot_bgcolor='#4E5D6C',
)
)
fig.show()
I found my way here because I wanted to change the theme of my Choroplethmapbox. The accepted solution helped, but ultimately I found the code below worked for my situation:
instantiate figure
fig = go.Figure()
add some traces
fig.add_trace(go.Choroplethmapbox(geojson=data_for_choropleth_geojson,
locations=data_for_choropleth['fips'],
z=data_for_choropleth['total_population'],
featureidkey='properties.fips'
))
finally, change the theme using update_layout
fig.update_layout(
hovermode='closest',
mapbox=dict(
# style options: "basic", "streets", "outdoors",
# "dark", "satellite", or "satellite-streets","light"
# "open-street-map", "carto-positron",
# "carto-darkmatter", "stamen-terrain",
# "stamen-toner" or "stamen-watercolor"
style='light',
bearing=0,
pitch=0,
accesstoken=TOKEN,
zoom=5,
center=dict(
lat=29.4652568,
lon=-98.613121
)
)
Related
I am trying to mark some points on a map. But I would like to zoom in automatically. So I use the following code which works perfectly fine for go.Scattergeo plot.
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
margin = 0.002
fig.update_layout(
title = 'Something',
autosize=False,
width=800,
height=600,
geo = dict(
# projection_scale=8000, #this is kind of like zoom
lonaxis = dict(
range= [ df['longitude'].min()-margin, df['longitude'].max()+margin ],
dtick = 5
),
lataxis = dict (
range= [ df['latitude'].min()-margin, df['latitude'].max()+margin ],
dtick = 5
)
)
)
But when change the plot to mapbox, the lataxis and lonaxis seem not working anymore.
# fig = px.scatter_mapbox(df,
# lat="latitude",
# lon="longitude",
# color="rssi",
# color_continuous_scale=px.colors.cyclical.IceFire)
fig = go.Figure(go.Scattermapbox(
lon = df['longitude'],
lat = df['latitude'],
mode = 'markers',
marker = dict(
autocolorscale = False,
colorscale = 'icefire',
color = df['rssi'],
)))
fig.update_layout(mapbox_style="open-street-map")
Any idea how can make it work? Or how can zoom in and center graph? Any help is appreciated.
I have made a scatter plot using matplotlib and Plotly. I want the height, width and the markers to be scatter as in matplotlib plot. Please see the attached plots.
I used the following code in Plotly
import plotly
import plotly.plotly as py
from plotly.graph_objs import Scatter
import plotly.graph_objs as go
trace1 = go.Scatter(
x=x1_tsne, # x-coordinates of trace
y=y1_tsne, # y-coordinates of trace
mode='markers ', # scatter mode (more in UG section 1)
text = label3,
opacity = 1,
textposition='top center',
marker = dict(size = 25, color = color_4, symbol = marker_list_2, line=dict(width=0.5)),
textfont=dict(
color='black',
size=18, #can change the size of font here
family='Times New Roman'
)
)
layout = {
'xaxis': {
'showticklabels': False,
'showgrid': False,
'zeroline': False,
'linecolor':'black',
'linewidth':2,
'mirror':True,
'autorange':False,
'range':[-40, 40][![enter image description here][1]][1]
},
'yaxis': {
'showticklabels': False,
'showgrid': False,
'zeroline': False,
'linecolor':'black',
'linewidth':2,
'mirror':True,
'autorange':False,
'range':[-40, 40]
}
}
data = [trace1]
fig = go.Figure(
data= data,
layout= layout)
py.iplot(fig)
I try to tune the range but did not help. In addition, I use Autorange that did not help. Could you please help me with this.
I want the image as
##update: This can be done by the following code. I am updating this in the question:
trace1 = go.Scatter(
x=x1_tsne, # x-coordinates of trace
y=y1_tsne, # y-coordinates of trace
mode='markers +text ', # scatter mode (more in UG section 1)
text = label3,
opacity = 1,
textposition='top center',
marker = dict(size = 25, color = color_4, symbol = marker_list_2, line=dict(width=0.5)),
textfont=dict(
color='black',
size=18, #can change the size of font here
family='Times New Roman'
)
)
data = [trace1]
layout = go.Layout(
autosize=False,
width=1000,
height=1000,
xaxis= go.layout.XAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
yaxis= go.layout.YAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
margin=go.layout.Margin(
l=50,
r=50,
b=100,
t=100,
pad = 4
)
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='size-margins')
Have you considered to use
fig.update_layout(
autosize=False,
width=800,
height=800,)
and eventually reduce the size of your marker?
UPDATE
Full Code
import plotly.graph_objs as go
trace1 = go.Scatter(
x=x1_tsne, # x-coordinates of trace
y=y1_tsne, # y-coordinates of trace
mode='markers +text ', # scatter mode (more in UG section 1)
text = label3,
opacity = 1,
textposition='top center',
marker = dict(size = 12, color = color_4, symbol = marker_list_2, line=dict(width=0.5)),
textfont=dict(
color='black',
size=18, #can change the size of font here
family='Times New Roman'
)
)
data = [trace1]
layout = go.Layout(
autosize=False,
width=1000,
height=1000,
xaxis= go.layout.XAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
yaxis= go.layout.YAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
margin=go.layout.Margin(
l=50,
r=50,
b=100,
t=100,
pad = 4
)
)
fig = go.Figure(data=data, layout=layout)
Let's take this sample dataframe :
import random
df=pd.DataFrame({'Id':list(range(1,101)), 'Value':[random.randint(0,50) for i in range(100)]})
I would like to create a plotly express strip plot in which id 5 and 10 are colored in red and the others in blue. I built the following function :
import plotly.express as px
def strip_plotly(df,col_value,col_hover=[],col_color=None,L_color=[]):
if col_color is not None :
L_color = ["red" if i in L_color else "blue" for i in df[col_color].values]
else :
L_color = ["blue"]*len(df.index)
fig = px.strip(df, y=col_value,hover_data = col_hover,color_discrete_sequence = L_color)
fig.update_layout({
'plot_bgcolor': 'rgba(0,0,0,0)',
'paper_bgcolor': 'rgba(0,0,0,0)',
},
hoverlabel=dict(
#bgcolor="white",
font_size=12,
#font_family="Rockwell"
),
xaxis={
'title':"x",
#'type':'log'
},
yaxis={'title':"y"},
title={
'text': "strip plot for stackoverflow",
#'y':0.95,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top'}
)
fig.update_xaxes(showspikes=True, spikecolor = 'black', showline=True, linewidth=1,linecolor='black',
ticks = "outside", tickwidth = 1, tickcolor = 'black',ticklen = 5)
fig.update_yaxes(showspikes=True, spikecolor = 'black', showline=True, linewidth=1,linecolor='black',
ticks = "outside", tickwidth = 1, tickcolor = 'black',ticklen = 5)
fig.show()
But when I run the function :
strip_plotly(df,"Value",col_hover=["Id"],col_color="Id",L_color=[5,10])
I get only blue points (ids 5 and 10 are not red). Would you please explain me what's wrong ?
have reduced size of data frame just to make it clear red points are there...
you need two traces as color is only one per trace https://plotly.github.io/plotly.py-docs/generated/plotly.graph_objects.box.marker.html
to make traces line up have also defined offsetgroup
import random
import plotly.express as px
import numpy as np
import pandas as pd
df=pd.DataFrame({'Id':list(range(1,21)), 'Value':[random.randint(0,50) for i in range(20)]})
def strip_plotly(df,col_value,col_hover=[],col_color=None,L_color=[]):
L_color = np.where(df["Id"].isin([5,10]), "red", "blue")
# need two traces as color is in marker https://plotly.github.io/plotly.py-docs/generated/plotly.graph_objects.box.marker.html
fig = px.strip(df.loc[L_color=="blue"], y=col_value,hover_data = col_hover,color_discrete_sequence = ["blue"])
fig = fig.add_traces(px.strip(df.loc[L_color=="red"], y=col_value,hover_data = col_hover,color_discrete_sequence = ["red"]).data)
fig = fig.update_traces(offsetgroup="1")
fig.update_layout({
'plot_bgcolor': 'rgba(0,0,0,0)',
'paper_bgcolor': 'rgba(0,0,0,0)',
},
hoverlabel=dict(
#bgcolor="white",
font_size=12,
#font_family="Rockwell"
),
xaxis={
'title':"x",
#'type':'log'
},
yaxis={'title':"y"},
title={
'text': "strip plot for stackoverflow",
#'y':0.95,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top'}
)
fig.update_xaxes(showspikes=True, spikecolor = 'black', showline=True, linewidth=1,linecolor='black',
ticks = "outside", tickwidth = 1, tickcolor = 'black',ticklen = 5)
fig.update_yaxes(showspikes=True, spikecolor = 'black', showline=True, linewidth=1,linecolor='black',
ticks = "outside", tickwidth = 1, tickcolor = 'black',ticklen = 5)
return fig.show()
strip_plotly(df,"Value",col_hover=["Id"],col_color="Id",L_color=[5,10])
Here's a much simpler solution.
Create a 'color' column with the desired color
Assign colors based on the values of that column (creates a separate trace for each color)
Overlay traces on top of each other
df=pd.DataFrame({'Id':list(range(1,101)), 'Value':[random.randint(0,50) for i in range(100)]})
df['color'] = np.where(df['Id'].isin([5,10]), 'red', 'blue')
fig = px.strip(df, y='Value', color='color')
fig.update_traces(offsetgroup=0)
fig.show()
x2016 = data[data.year == 2016].iloc[:20,:]
num_students_size = [float(each.replace(',', '.')) for each in x2016.num_students]
international_color = [float(each) for each in x2016.international]
trace1 = go.Scatter(
x = x2016.world_rank,
y = x2016.teaching,
mode = "markers",
marker=dict(
color = international_color,
size = num_students_size,
showscale = True
),
text = x2016.university_name
)
data5 = [trace1]
iplot(data5)
This gives bubble plot and it does not show labels . How to add labels please help]1
Your [data5] would be better suited as a go.Figure() object.
There is a good sequence here to follow: https://plotly.com/python/line-and-scatter/#bubble-scatter-plots
Here is the reference to figure labels:
https://plotly.com/python/figure-labels/
fig.update_layout(
title="Plot Title",
xaxis_title="x Axis Title",
yaxis_title="y Axis Title",
font=dict(
family="Courier New, monospace",
size=18,
color="#7f7f7f"
)
)
fig.show()
Additional relevant help and tutorials here:
https://plotly.com/python/line-and-scatter/
So - to give a generic hint here, something like the following should work:
data5 = go.Figure(data=trace1,
title="Plot Title",
xaxis_title="x Axis Title",
yaxis_title="y Axis Title"
)
iplot(data5)
I was doing some funnel plot using plotly, however, when I wanted to show the texts outside the box there is no text in left side and there is text in only right side.
setup
from plotly import graph_objects as go
stages = ["Homepage visit", "Search page visit",
"Payment Page", "Payment Confirmation"]
fig = go.Figure()
fig.add_trace(go.Funnel(
name = 'Desktop',
y = stages,
x = [30100, 27090, 2860, 150],
textposition = "outside",
textinfo = "value+percent previous"))
fig.add_trace(go.Funnel(
name = 'Mobile',
orientation = "h",
y = stages,
x = [15100, 12080, 2718, 302],
textposition = "outside",
textinfo = "value+percent previous"))
fig.show()
output
required
I want to see all the numbers. I tried both 'inside' and 'outside' but I was unable to see ALL the numbers.
this is not it, but it is something in this path, try exploring constraintext and text formatting:
from plotly import graph_objects as go
stages = ["Homepage visit", "Search page visit",
"Payment Page", "Payment Confirmation"]
fig = go.Figure()
fig.add_trace(go.Funnel(
name = 'Desktop',
y = stages,
x = [30100, 27090, 2860, 150],
textposition = "inside",
textinfo = "value+percent previous"
, constraintext='outside'
,textfont=dict(
family="sans serif",
size=14,
color="black"
)
)
)
fig.add_trace(go.Funnel(
name = 'Mobile',
orientation = "h",
y = stages,
x = [15100, 12080, 2718, 302],
textposition = "auto",
textinfo = "value+percent previous"))
fig.show()