Editing:
The following example from Plotly for reference:
import plotly.express as px
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
fig = px.bar(df, y='pop', x='country', text='pop')
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')
fig.show()
How to remove the word 'pop'.
What I want to hide the y-axis title of'value'.
The following syntax doesn't work.
fig.update_yaxes(showticklabels=False)
Thanks.
Solution
You need to use visible=False inside fig.update_yaxes() or
fig.update_layout() as follows. For more details see the
documentation for plotly.graph_objects.Figure.
# Option-1: using fig.update_yaxes()
fig.update_yaxes(visible=False, showticklabels=False)
# Option-2: using fig.update_layout()
fig.update_layout(yaxis={'visible': False, 'showticklabels': False})
# Option-3: using fig.update_layout() + dict-flattening shorthand
fig.update_layout(yaxis_visible=False, yaxis_showticklabels=False)
Try doing the following to test this:
# Set the visibility ON
fig.update_yaxes(title='y', visible=True, showticklabels=False)
# Set the visibility OFF
fig.update_yaxes(title='y', visible=False, showticklabels=False)
A. How to create the figure directly with hidden-yaxis label and tickmarks
You can do this directly by using the layout keyword and
supplying a dict to go.Figure() constructor.
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Bar(y=[2, 1, 3])],
layout_title_text="A Figure Displaying Itself",
layout = {'xaxis': {'title': 'x-label',
'visible': True,
'showticklabels': True},
'yaxis': {'title': 'y-label',
'visible': False,
'showticklabels': False}
}
)
fig
B. How to create the figure without the margin space around
Say, you suppressed the titles for both the axes. By default plotly
would still leave a default amount of space all around the figure:
this is known as the margin in Plotly's documention.
What if you want to reduce or even completely remove the margin?
This can be done using fig.update_layout(margin=dict(l = ..., r = ..., t = ..., b = ...)) as mentioned in the documentation:
https://plotly.com/python/reference/#layout-margin.
In the following example, I have reduced the left, right
and bottom margins to 10 px and set the top margin to 50 px.
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Bar(y=[2, 1, 3])],
layout_title_text="A Figure with no axis-title and modified margins",
layout = {
'xaxis': {'title': 'x-label',
'visible': False,
'showticklabels': True},
'yaxis': {'title': 'y-label',
'visible': False,
'showticklabels': False},
# specify margins in px
'margin': dict(
l = 10, # left
r = 10, # right
t = 50, # top
b = 10, # bottom
),
},
)
fig
C. An Interesting Feature of Plotly: A hidden shorthand
It turns out that Plotly has a convenient shorthand notation
allowing dict-flattening available for input arguments such as this:
## ALL THREE METHODS BELOW ARE EQUIVALENT
# No dict-flattening
# layout = dict with yaxis as key
layout = {'yaxis': {'title': 'y-label',
'visible': False,
'showticklabels': False}
}
# Partial dict-flattening
# layout_yaxis = dict with key-names
# title, visible, showticklabels
layout_yaxis = {'title': 'y-label',
'visible': False,
'showticklabels': False}
# Complete dict-flattening
# layout_yaxis_key-name for each of the key-names
layout_yaxis_title = 'y-label'
layout_yaxis_visible = False
layout_yaxis_showticklabels = False
Now try running all three of the following and compare the outputs.
import plotly.graph_objects as go
# Method-1: Shortest (less detailed)
fig = go.Figure(
data=[go.Bar(y=[2, 1, 3])],
layout_title_text="A Figure Displaying Itself",
layout_yaxis_visible = False,
layout_xaxis_title = 'x-label'
)
fig.show()
# Method-2: A hibrid of dicts and underscore-separated-syntax
fig = go.Figure(
data=[go.Bar(y=[2, 1, 3])],
layout_title_text="A Figure Displaying Itself",
layout_xaxis_title = 'x-label',
layout_yaxis = {'title': 'y-label',
'visible': False,
'showticklabels': False}
)
fig.show()
# Method-3: A complete dict syntax
fig = go.Figure(
data=[go.Bar(y=[2, 1, 3])],
layout_title_text="A Figure Displaying Itself",
layout = {'xaxis': {'title': 'x-label',
'visible': True,
'showticklabels': True},
'yaxis': {'title': 'y-label',
'visible': False,
'showticklabels': False}
}
)
fig.show()
How to remove the word 'pop'?
Just pass yaxis_title=None to fig.update_layout to hide default title of Y axis (similarly for xaxis_title=None for X axis).
import plotly.express as px
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
fig = px.bar(df, y='pop', x='country', text='pop')
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide', yaxis_title=None)
fig.show()
Related
I have the following code which works well:
import plotly.graph_objects as go
fig = go.Figure(go.Scattermapbox(
mode = "markers+lines",
lon = [-74.164556, -73.214697],
lat = [41.515941, 41.474395],
marker = {'size': 10}))
fig.update_layout(
margin ={'l':0,'t':0,'b':0,'r':0},
mapbox = {
'center': {'lon': 10, 'lat': 10},
'style': "stamen-terrain",
'center': {'lon': -20, 'lat': -20},
'zoom': 1})
fig.show()
Result:
I am now trying to add multiple lines from my dataframe but am not having any luck. This is what I am trying (have highlighted the new areas):
import plotly.graph_objects as go
Start_Lat = data['Start_Lat'] ## New code
Start_Lng = data['Start_Lng'] ## New code
End_Lat = data['End_Lat'] ## New code
End_Lng = data['End_Lng'] ## New code
fig = go.Figure(go.Scattermapbox(
mode = "markers+lines",
lat = [Start_Lat, End_Lat], ## New code
lon = [Start_Lng, End_Lng], ## New code
marker = {'size': 10}))
fig.update_layout(
margin ={'l':0,'t':0,'b':0,'r':0},
mapbox = {
'center': {'lon': 10, 'lat': 10},
'style': "stamen-terrain",
'center': {'lon': -20, 'lat': -20},
'zoom': 1})
fig.show()
The data looks like this:
Is anybody able to tell me what I am doing wrong here?
Thank you :)
With your data format, it's best to loop over the start and end coordinate pairs. Otherwise I think it should be a list with alternating start and end coordinates.
import plotly.graph_objects as go
fig = go.Figure()
for row in data.itertuples():
fig.add_trace(go.Scattermapbox(
mode = "markers+lines",
lat = [row.Start_Lat, row.End_Lat],
lon = [row.Start_Lng, row.End_Lng],
marker = {'size': 10}))
fig.update_layout(
margin ={'l':0,'t':0,'b':0,'r':0},
mapbox = {
'center': {'lon': data['Start_Lng'].mean(), 'lat': data['Start_Lat'].mean()},
'style': "stamen-terrain",
'zoom': 5.5})
fig.show()
i am trying to compare two lines in the same fig in plotly go, the goal is to let the user to select two entities (i.e. countries) from two dropdown menu in the chart
this is the chart with all entities active
when i select different country in the two dropdown:
i.e. dropdown1 = Italy, dropdown2= France
the chart shows just one line (the last selected from the dropdown, so it update)but it doesn't plot the two lines in the same figure
Plot with just one line
this is the dataframe:
dataframe head
this is the code i am working on:
fig1 = go.Figure()
for column in df.columns.to_list():
fig1.add_trace(
go.Scatter(
x = df.index,
y = df[column],
name = column
)
)
button_all = dict(label = 'All',
method = 'restyle',
args = [{'visible': df.columns.isin(df.columns),
'title': 'All',
'showlegend':True}])
button_none = dict(label = 'None',
method = 'update',
args = [{'visible': df.columns.isin(df.columns),
'title': 'All',
'showlegend':True}])
def create_layout_button(column):
return dict(label = column,
method = 'restyle',
args = [{'visible': df.columns.isin([column]),
'title': column,
'showlegend': True}])
def create_layout_buttonE(column):
return dict(label = column,
method = 'update',
args = [{'visible': df.columns.isin([column]),
'title': column,
'showlegend': True}])
addAll = True
# Update plot sizing
fig1.update_layout(
width=700,
height=500,
autosize=False,
margin=dict(t=120, b=0, l=0, r=0),
)
# Add dropdowns
button_layer_1_height = 1.08
fig1.update_layout(
updatemenus=[
dict(
buttons=([button_all] * addAll) + list(df.columns.map(lambda column: create_layout_button(column))),
direction="down",
pad={"r": 10, "t": 0},
showactive=True,
x=0.1,
xanchor="left",
y=button_layer_1_height,
yanchor="top"
),
dict(
buttons=([button_none] * addAll) + list(df.columns.map(lambda column: create_layout_buttonE(column))),
direction="down",
pad={"r": 10, "t": 0},
showactive=True,
x=0.37,
xanchor="left",
y=button_layer_1_height,
yanchor="top"
),
]
)
fig1.show()
synthesized dataframe in same structure as you defined
taken a different approach. Rather than creating all traces and controlling visibility in updatemenus. Create two traces and control name and contents of y in updatemenus
import pandas as pd
import numpy as np
import plotly.graph_objects as go
# get some countries
countries = (
pd.read_csv(
"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/locations.csv"
)
.loc[lambda d: d["iso_code"].str.len() == 3, "location"]
.sample(20)
.sort_values()
.values
)
# build data frame of same struct
df = pd.DataFrame(
np.random.randint(200, 1500, [22, len(countries)]),
columns=countries,
index=range(2000, 2022),
)
# create a figure with two place holder traces
fig = go.Figure(
[
go.Scatter(x=df.index, y=np.full(len(df), np.nan), meta=i, name=i)
for i in range(2)
]
)
# but data for y and name in when country is selected
fig.update_layout(
updatemenus=[
{
"x": b / 3,
"y": 1.4,
"active": None,
"buttons": [
{
"label": c,
"method": "restyle",
"args": [{"y": [df[c]], "name": c}, [b]],
}
for c in df.columns
],
}
for b in range(2)
]
)
I have a plotly histogram with a shape in the background. How can I make the background object right/left dragg-able?
import numpy as np
import plotly.graph_objects as go
# generate data
data = np.random.normal(0,10,500)
# plot histogramm
fig = go.Figure()
fig.add_trace(go.Histogram(x=data))
# add shape
fig.add_shape(dict(type="rect", xref="x", yref="paper",
x0=-22, x1=22,
y0=0, y1=1,
fillcolor="Gray", opacity=0.3,
layer="below", line_width=0, editable=True))
current output:
desired output: have the shape-object draggable.
Edit: The background object doesnt have to be a "shape"
Disclaimer: I am not very experienced in Dash, but this was the only way I could implement a movable shape. I relied heavily on this answer by chriddyp in the Plotly Community forum. The parameters of dcc.Graph are pretty similar to go.Figure.
One thing to note is that only when your cursor is very much interior to the shape are you able to drag it, but if you hover anywhere else closer to the borders, clicking and dragging will change your shape's dimensions rather than move it, which may or may not not be the behavior you are after. Anyone who uses Dash regularly- feel free to update/improve upon my answer as needed.
import numpy as np
import json
from textwrap import dedent as d
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
# generate data, set seed for reproducibility
np.random.seed(42)
data = np.random.normal(0,10,500)
app = dash.Dash(
__name__,
external_stylesheets=[
'https://codepen.io/chriddyp/pen/dZVMbK.css'
]
)
styles = {'pre': {'border': 'thin lightgrey solid', 'overflowX': 'scroll'}}
app.layout = html.Div(className='row', children=[
dcc.Graph(
id='basic-interactions',
className='six columns',
figure={
'data': [{
'x': data,
'name': 'Trace 1',
'type': 'histogram'
}],
'layout': {
'shapes': [{
'type': 'rect',
'x0': -22,
'x1': 22,
'xref': 'x',
'y0': 0,
'y1': 50,
'yref': 'y',
'fill': 'toself',
'line': dict(
color="Gray",
width=0.5,
),
'fillcolor': 'Gray',
'layer': 'below'
}]
}
},
config={
'editable': True,
'edits': {
'shapePosition': True
}
}
),
])
if __name__ == '__main__':
app.run_server(debug=True)
I created a dropdown menu with several graphs and everything is fine but when I start the program and have not yet selected one of the buttons, I see all the graphs and it just looks messy so I want to change this. In the default situation I would like to see only the graph that is connected to the first button. I tried to do this with the line "active = 0" but it only caused the first button to be highlighted.
Here is a snippet of my data (it shows the effect of the corona crisis on the sales index in the german manufacturing industry):
Chemicals;Mechanical engineering;Motor vehicles and motor vehicle parts;Dates
101.5;108.1;104.6;Jan-2019
101.2;105.8;105.9;Feb-2019
101;105.9;106.2;Mar-2019
101;105.6;101.2;Apr-2019
99.3;103.2;104.5;Mai-2019
99.4;103;101.9;Jun-2019
99.2;104;99.5;Jul-2019
99.4;103;102.2;Aug-2019
97.1;102.7;102.2;Sept-2019
99.7;100.6;100.9;Okt-2019
99.1;101.8;100.4;Nov-2019
98.7;99.7;101.6;Dez-2019
99.2;102.4;100.1;Jan-2020
101.5;100.1;99.8;Feb-2020
99.2;91.5;72.7;Mar-2020
90;73.9;24.8;Apr-2020
And here is a simple version of my program:
import plotly.graph_objects as go
import numpy as np
import pandas as pd
df = pd.read_csv("sales_index_manufacturing.csv", delimiter = ";")
fig = go.Figure()
fig.add_trace(
go.Scatter(x=list(df['Dates']),
y=list(df['Chemicals']),
name="Chemicals",
line=dict(color="#008b8b"))
)
fig.add_trace(
go.Scatter(x=list(df['Dates']),
y=list(df['Mechanical engineering']),
name='Mechanical engineering',
line=dict(color="#8b008b"))
)
fig.add_trace(
go.Scatter(x=list(df['Dates']),
y=list(df['Motor vehicles and motor vehicle parts']),
name='Motor vehicles and motor vehicle parts',
line=dict(color="#ffa500"))
)
fig.update_layout(
updatemenus=[
dict(
active= 0,
buttons=list([
dict(label='Chemicals',
method="update",
args=[{"visible": [True,False,False]},
{"title": "Chemicals",
"annotations": [],
'yaxis': {'title': 'sales index (2015 = 100)'}}]),
dict(label='Mechanical engineering',
method="update",
args=[{"visible": [False,True,False]},
{"title": 'Mechanical engineering',
"annotations": [],
'yaxis': {'title': 'sales index (2015 = 100'}}]),
dict(label='Motor vehicles and motor vehicle parts',
method="update",
args=[{"visible": [False,False,True]},
{"title": "Motor vehicles and motor vehicle parts",
"annotations": [],
'yaxis': {'title': 'sales index (2015 = 100)'}}]
)]
),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=-0.04,
xanchor="left",
y=1.132,
yanchor="top",
)
])
fig.update_layout(
legend=dict(x= 0.75,
y=1.1,
bgcolor='rgba(255, 255, 255, 0)',
bordercolor='rgba(255, 255, 255, 0)'),
width=1000,
height=600,
autosize=False,
template="plotly_white",
)
fig.show()
When you run the code, you're probably wondering what I mean by "messy," but the original program contains a lot more graphs and data, and it really looks like a mess in the default situation.
Thanks in advance for your help!
Based on this code directly from plotly's tut page:
https://plot.ly/python/dropdowns/
Now, what if I want to change not just the chart type but rather the data source and its chart type?
Is it possible?
EDIT:
I've played with this settings:
data1 = go.Surface(z=df.values.tolist(), colorscale='Viridis')
data2 = go.Heatmap(z=df.values.tolist())
buttons=list([
dict(
args=[data1],
label='3D Surface',
method='restyle'
),
dict(
args=[data2],
label='Heatmap',
method='restyle'
)
])
However, the graphs are shown, but overlayed. And when I click any item in the dropdown menu, the graph is completely gone.
I've found a solution myself, that is actually based on the tut:
import plotly
import plotly.graph_objs as go
from datetime import datetime
import pandas_datareader as web
df = web.DataReader("aapl", 'google',
datetime(2015, 1, 1),
datetime(2016, 7, 1))
trace_high = go.Bar( x=df.index,
y=df.High,
name='High')
trace_low = go.Scatter(x=df.index,
y=df.Low,
name='Low',
line=dict(color='#F06A6A'))
data = [trace_high, trace_low]
updatemenus = list([
dict(active=-1,
buttons=list([
dict(label = 'High',
method = 'update',
args = [{'visible': [True, False]},
{'title': 'Yahoo High'}]),
dict(label = 'Low',
method = 'update',
args = [{'visible': [False, True]},
{'title': 'Yahoo Low'}])
]),
)
])
layout = dict(title='Yahoo', showlegend=False,
updatemenus=updatemenus)
fig = dict(data=data, layout=layout)
plotly.offline.plot(fig, auto_open=False, show_link=False)