Say I have the following figure:
import numpy as np
import plotly.graph_objs as go
z=np.random.randint(1000, 11000, size=20)
trace=dict(type='scatter',
x=3+np.random.rand(20),
y=-2+3*np.random.rand(20),
mode='markers',
marker=dict(color= z,
colorscale='RdBu', size=14, colorbar=dict(thickness=20)))
axis_style=dict(zeroline=False, showline=True, mirror=True)
layout=dict(width=550, height=500,
xaxis=axis_style,
yaxis=axis_style,
hovermode='closest',
)
fig=go.FigureWidget(data=[trace], layout=layout)
fig
Now say I want the colorbar to have a title. Since plotly does not currently have a direct way to do that, if I understand correctly, I am doing this through annotations as shown here:
layout.update(
annotations=[dict(
x=1.12,
y=1.05,
align="right",
valign="top",
text='Colorbar Title',
showarrow=False,
xref="paper",
yref="paper",
xanchor="center",
yanchor="top"
)
]
)
As we can see, the colorbar title appears:
fig=go.FigureWidget(data=[trace], layout=layout)
fig
However, now say I want to place the colorbar title sideways, along the colorbar, like so:
How do I do this?
Parameter textangle do it for you. Example from plotly docs. Setting textangle=-90 rotate annotation how you want.
Code:
# import necessaries libraries
import numpy as np
import plotly.offline as py
import plotly.graph_objs as go
z = np.random.randint(1000, 11000, size=20)
# Create a trace
trace = dict(type='scatter',
x=3+np.random.rand(20),
y=-2+3*np.random.rand(20),
mode='markers',
marker=dict(color=z, colorscale='RdBu',
size=14, colorbar=dict(thickness=20)))
# Define axis_style
axis_style = dict(zeroline=False, showline=True, mirror=True)
# Specify layout style
layout = dict(width=550, height=500,
xaxis=axis_style,
yaxis=axis_style,
hovermode='closest',
)
# Update layout with annotation
layout.update(
annotations=[dict(
# Don't specify y position,because yanchor="middle" do it for you
x=1.22,
align="right",
valign="top",
text='Colorbar Title',
showarrow=False,
xref="paper",
yref="paper",
xanchor="right",
yanchor="middle",
# Parameter textangle allow you to rotate annotation how you want
textangle=-90
)
]
)
# Create FigureWidget
fig = go.FigureWidget(data=[trace], layout=layout)
# Plot fig
py.plot(fig)
Output:
For anyone who may have found this question now, there is (now?) a very easy way of adding a title to a colorbar, and to make it oriented sideways along the colorbar using the colorbar title property.
In this case, we could just update trace like so:
# Create a trace
trace = dict(type='scatter',
x=3+np.random.rand(20),
y=-2+3*np.random.rand(20),
mode='markers',
marker=dict(color=z, colorscale='RdBu', size=14,
colorbar=dict(thickness=20,
title=dict(text="Colorbar title", orient="right"))))
Documentation here: https://plotly.com/python/reference/scatter/#scatter-marker-colorbar
Related
I would like to plot several plots in a subplot, specifically ecdf plots which are found under plotly express. Unfortunately I cannot get it to work because it appears subplot expects a graph objects plotly plot. The error says it receives invalid data, specifically:
"Invalid element(s) received for the 'data' property"
Obviously that means that of the following, ecdf is not included:
['bar', 'barpolar', 'box', 'candlestick',
'carpet', 'choropleth', 'choroplethmapbox',
'cone', 'contour', 'contourcarpet',
'densitymapbox', 'funnel', 'funnelarea',
'heatmap', 'heatmapgl', 'histogram',
'histogram2d', 'histogram2dcontour', 'icicle',
'image', 'indicator', 'isosurface', 'mesh3d',
'ohlc', 'parcats', 'parcoords', 'pie',
'pointcloud', 'sankey', 'scatter',
'scatter3d', 'scattercarpet', 'scattergeo',
'scattergl', 'scattermapbox', 'scatterpolar',
'scatterpolargl', 'scatterternary', 'splom',
'streamtube', 'sunburst', 'surface', 'table',
'treemap', 'violin', 'volume', 'waterfall']
Great, now, is there a work around that will allow me to plot a few of these guys next to each other?
Here's the code for a simple ecdf plot as from the documentation.
import plotly.express as px
df = px.data.tips()
fig = px.ecdf(df, x="total_bill", color="sex", markers=True, lines=False, marginal="histogram")
fig.show()
If I wanted to plot two of this same plot together for example, I would expect the following code (basically copied from the documentation) to work, probably, (if it accepted ecdf) but I cannot get it to work for the aforementioned reasons.
from plotly.subplots import make_subplots
import plotly.graph_objects as go
df = px.data.tips()
fig = make_subplots(rows=1, cols=2)
fig.add_trace(
px.ecdf(df, x="total_bill", color="sex", markers=True, lines=False, marginal="histogram"),
row=1, col=1
)
fig.add_trace(
px.ecdf(df, x="total_bill", color="sex", markers=True, lines=False, marginal="histogram"),
row=1, col=2
)
fig.update_layout(height=600, width=800, title_text="Side By Side Subplots")
fig.show()
Is there a work around for px.ecdf subplots?
Thank you in advance!
ECDF plots follow the Plotly Express pattern of having face_col parameter https://plotly.com/python-api-reference/generated/plotly.express.ecdf.html
simplest way to achieve this is to prepare the dataframe for this capability. In this example have created two copies of the data with each copy having a column for this capability
alternative is far more complex, both make_subplots() and px.ecdf() create multiple x and y axis. It would be necessary to manage all of these yourself
import plotly.express as px
import pandas as pd
df = px.data.tips()
df = pd.concat([px.data.tips().assign(col=c) for c in ["left","right"] ])
fig = px.ecdf(df, x="total_bill", color="sex", markers=True, lines=False, marginal="histogram", facet_col="col")
fig.update_layout(height=600, width=800, title_text="Side By Side Subplots")
I want to add a caption below my plotly choropleth Map (using Python). I've looked into using annotations with graph_objs, but it only seems to work for locations within the map area. Is there a way to make the annotations show up below the choropleth map and/or is there an alternative way of doing this?
Right now I'm getting this but would like the caption to appear below the map area:
I've tried inputting y values less than 0, but then the text annotations just don't show up at all.
Here's my code:
import plotly.graph_objects as go
import pandas as pd
import plotly
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
fig = go.Figure(data=go.Choropleth(
locations = df['CODE'],
z = df['GDP (BILLIONS)'],
text = df['COUNTRY'],
colorscale = 'Blues',
autocolorscale=False,
reversescale=True,
marker_line_color='darkgray',
marker_line_width=0.5,
colorbar_tickprefix = '$',
colorbar_title = 'GDP<br>Billions US$',
))
fig.update_layout(
title_text='2014 Global GDP',
geo=dict(
showframe=False,
showcoastlines=False,
projection_type='equirectangular'
),
annotations = [dict(
x=0.5,
y=0, #Trying a negative number makes the caption disappear - I'd like the caption to be below the map
xref='paper',
yref='paper',
text='Source: <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
CIA World Factbook</a>',
showarrow = False
)]
)
fig.show()
Setting y=-0.1 works fine on my end:
Plot 1
If that for some reason is not the case on your end (perhaps a version issue?), you should try to just leave it at y=0 and rather make room below the figure utself by adjustin the margins of the plot like this:
fig.update_layout(
margin=dict(l=20, r=20, t=60, b=20),
paper_bgcolor="LightSteelBlue")
Plot 2:
Complete code:
import plotly.graph_objects as go
import pandas as pd
import plotly
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
fig = go.Figure(data=go.Choropleth(
locations = df['CODE'],
z = df['GDP (BILLIONS)'],
text = df['COUNTRY'],
colorscale = 'Blues',
autocolorscale=False,
reversescale=True,
marker_line_color='darkgray',
marker_line_width=0.5,
colorbar_tickprefix = '$',
colorbar_title = 'GDP<br>Billions US$',
))
fig.update_layout(
title_text='2014 Global GDP',
geo=dict(
showframe=False,
showcoastlines=False,
projection_type='equirectangular'
),
annotations = [dict(
x=0.5,
y=0, #Trying a negative number makes the caption disappear - I'd like the caption to be below the map
xref='paper',
yref='paper',
text='Source: <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
CIA World Factbook</a>',
showarrow = False
)]
)
fig.update_layout(
margin=dict(l=20, r=20, t=60, b=20),
paper_bgcolor="LightSteelBlue")
fig.show()
I'm working with a Dash graph object and I'm fairly new to it. I'm attempting to pass in a graph that has 2 scatter charts and a bar chart on the same figure but I'd like the bar chart (green) to be on it's own secondary y axis so it looks better than it does here:
Now from what I understand about Dash, I have to pass a go.Figure() object so I have a function which defines the data and the layout. I saw in the plotly documentation that you can use plotly express add secondary axis but I'm not sure how to do that within my frame work here. Any help would be greatly appreciated!
Here's my code:
def update_running_graph(n_intervals):
df = pd.read_csv(filename)
trace1 = go.Scatter(x=df['Timestamp'],
y=df['CLE'],
name='Crude',
mode='lines+markers')
trace2 = go.Scatter(x=df['Timestamp'],
y=df['y_pred'],
name='Model',
mode='lines+markers')
trace3 = go.Bar(x=df['Timestamp'],
y=df['ModelDiff'],
name='Diff',
)
data = [trace1, trace2,trace3]
layout = go.Layout(title='CLE vs Model')
return go.Figure(data=data, layout=layout)
To add a secondary y-axis in dash you could do the following:
def update_running_graph(n_intervals):
df = pd.read_csv(filename)
trace1 = go.Scatter(x=df['Timestamp'],
y=df['CLE'],
name='Crude',
mode='lines+markers',
yaxis='y1')
trace2 = go.Scatter(x=df['Timestamp'],
y=df['y_pred'],
name='Model',
mode='lines+markers',
yaxis='y1')
trace3 = go.Bar(x=df['Timestamp'],
y=df['ModelDiff'],
name='Diff',
yaxis='y2'
)
data = [trace1, trace2,trace3]
layout = go.Layout(title='CLE vs Model',
yaxis=dict(title='Crude and Model'),
yaxis2=dict(title='Moddel Difference',
overlaying='y',
side='right'))
return go.Figure(data=data, layout=layout)
you can add more y-axis they always need to have the form of yi with i the i-th axis. Then in the layout you can specify the layout of the i-th axis with yaxisi=dict(...).
This documentation page should be of use. Just modify to fit your code, since trace1 and trace2 appear to be on the same scale, just set trace3 to the secondary axis scale and you should be set. Below is an example with just only 2 but adding a third should not be too difficult.
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])
# Add traces
fig.add_trace(
go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis data"),
secondary_y=False,
)
fig.add_trace(
go.Scatter(x=[2, 3, 4], y=[4, 5, 6], name="yaxis2 data"),
secondary_y=True,
)
# Add figure title
fig.update_layout(
title_text="Double Y Axis Example"
)
# Set x-axis title
fig.update_xaxes(title_text="xaxis title")
# Set y-axes titles
fig.update_yaxes(title_text="<b>primary</b> yaxis title", secondary_y=False)
fig.update_yaxes(title_text="<b>secondary</b> yaxis title", secondary_y=True)
fig.show()
Cheers!
I have a plotly offline chart with datetime and single y axis,now I want to add one more line in y axis.
original code:
from plotly.offline import download_plotlyjs,init_notebook_mode,plot
plot([Scatter(x=datetimefield,y=value1)],filename="plotly.html")
To add multiple I am tried to tweak the y parameter :
plot([Scatter(x=datecolumn,y=[value1,value2])],filename="plotly.html")
But this doesn't seems to be working.
x=datetime field is time series based
y=value1 & value 2 are two pandas columns
Note:- Two axis are in different datatype one is numeric other is percentage
How to tweak the y parameter in offline mode of plotly to have multiple axis.
Found solution:
from plotly.offline import download_plotlyjs,init_notebook_mode,plot
import plotly.graph_objs as go
trace1 = go.Scatter(
x=df.datetimecolumn,
y=df.value1)
trace2 = go.Scatter(
x=df.datetimecolumn,
y=df.value2)
data = [trace1, trace2]
layout = go.Layout(
xaxis=dict(
zeroline=True,
showline=True,
mirror='ticks',
gridcolor='#bdbdbd',
gridwidth=2,
zerolinecolor='#969696',
zerolinewidth=4,
linecolor='#636363',
linewidth=6
),
yaxis=dict(
zeroline=True,
showline=True,
mirror='ticks',
gridcolor='#bdbdbd',
gridwidth=2,
zerolinecolor='#969696',
zerolinewidth=4,
linecolor='#636363',
linewidth=6
)
)
fig = go.Figure(data=data, layout=layout)
plot(fig)
I'm producing a 3D surface plot with medium success, but some parameters just don't respond to my flags, such as axis ranges, labels and log scale, but some things do, such as overall title and aspect ratio. I can't understand the problem, can anyone see something I'm doing wrong?
Thanks
def make3dPlot(surfaceMatrix, regionStart, regionEnd):
data = [go.Surface(z=surfaceMatrix)]
#data = [go.Surface(z=[[1, 2, 3, 4, 9],[4, 1, 3, 7, 9],[5, 4, 7, 2, 9]])]
layout = go.Layout(
title=args.i,
autosize=True,
width=1600,
height=1000,
yaxis=dict(
title='Particle Size',
titlefont=dict(
family='Arial, sans-serif',
size=18,
color='lightgrey'
),
type='log',
autorange=True,
#range=[regionStart, RegionEnd]
),
xaxis=dict(
title="Genomic Co-ordinates",
titlefont=dict(
family='Arial, sans-serif',
size=18,
color='lightgrey'
),
#type='log',
#autorange=False,
range=[10, 15]#regionStart, regionEnd]
),
scene=dict(
aspectratio=dict(x=3, y=1, z=1),
aspectmode = 'manual'
)
)
fig = go.Figure(data=data, layout=layout)
plotly.offline.plot(fig)
With the Mock data it looks like this, with unchanged axis and no labels:
As per docs, xaxis, yaxis and zaxis for 3D plots in plotly are part of Scene, not Layout.
Example:
from plotly.offline import iplot, init_notebook_mode
import numpy as np
from plotly.graph_objs import Surface, Layout, Scene
init_notebook_mode()
x, y = np.mgrid[-2*np.pi:2*np.pi:300j, -2:2:300j]
surface = Surface(
x=x, y=y, z=-np.cos(x)+y**2/2
)
iplot([surface])
layout = Layout(scene=Scene(xaxis=dict(range=[-1,1])))
iplot(dict(data=[surface], layout=layout))
See also this question.