As a general rule, there are two ways to add text labels to figures:
Certain trace types, notably in the scatter family (e.g. scatter, scatter3d, scattergeo etc), support a text attribute, and can be displayed with or without markers.
Standalone text annotations can be added to figures using fig.add_annotation(), with or without arrows, and they can be positioned absolutely within the figure, or they can be positioned relative to the axes of 2d or 3d cartesian subplots i.e. in data coordinates.
The differences between these two approaches are that:
Traces can optionally support hover labels and can appear in legends.
Text annotations can be positioned absolutely or relative to data coordinates in 2d/3d cartesian subplots only.
Traces cannot be positioned absolutely but can be positioned relative to data coordinates in any subplot type.
Here is an example that creates a scatter plot with text labels using Plotly Express.
In [1]:
importplotly.expressaspxdf=px.data.gapminder().query("year==2007 and continent=='Americas'")fig=px.scatter(df,x="gdpPercap",y="lifeExp",text="country",log_x=True,size_max=60)fig.update_traces(textposition='top center')fig.update_layout(height=800,title_text='GDP and Life Expectancy (Americas, 2007)')fig.show()
Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash, click "Download" to get the code and run python app.py.
Sign up for Dash Club → Free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture.
Join now.
For the pie, bar-like, sunburst and treemap traces, it is possible to force all the text labels to have the same size thanks to the uniformtext layout parameter. The minsize attribute sets the font size, and the mode attribute sets what happens for labels which cannot fit with the desired fontsize: either hide them or show them with overflow.
Here is a bar chart with the default behavior which will scale down text to fit.
In [4]:
importplotly.expressaspxdf=px.data.gapminder(year=2007)fig=px.bar(df,x='continent',y='pop',color="lifeExp",text='country',title="Default behavior: some text is tiny")fig.update_traces(textposition='inside')fig.show()
Here is the same figure with uniform text applied: the text for all bars is the same size, with a minimum size of 8. Any text at the minimum size which does not fit in the bar is hidden.
In [5]:
importplotly.expressaspxdf=px.data.gapminder(year=2007)fig=px.bar(df,x='continent',y='pop',color="lifeExp",text='country',title="Uniform Text: min size is 8, hidden if can't fit")fig.update_traces(textposition='inside')fig.update_layout(uniformtext_minsize=8,uniformtext_mode='hide')fig.show()
In [6]:
importplotly.expressaspxdf=px.data.gapminder().query("continent == 'Asia' and year == 2007")fig=px.pie(df,values='pop',names='country')fig.update_traces(textposition='inside')fig.update_layout(uniformtext_minsize=12,uniformtext_mode='hide')fig.show()
The textfont_size parameter of the pie, bar-like, sunburst and treemap traces can be used to set the maximum font size used in the chart. Note that the textfont parameter sets the insidetextfont and outsidetextfont parameter, which can also be set independently.
In [7]:
importplotly.expressaspxdf=px.data.gapminder().query("continent == 'Asia' and year == 2007")fig=px.pie(df,values='pop',names='country')fig.update_traces(textposition='inside',textfont_size=14)fig.show()
Annotations can be added to a figure using fig.add_annotation().
In [8]:
importplotly.graph_objectsasgofig=go.Figure()fig.add_trace(go.Scatter(x=[0,1,2,3,4,5,6,7,8],y=[0,1,3,2,4,3,4,6,5]))fig.add_trace(go.Scatter(x=[0,1,2,3,4,5,6,7,8],y=[0,4,5,1,2,2,3,4,2]))fig.add_annotation(x=2,y=5,text="Text annotation with arrow",showarrow=True,arrowhead=1)fig.add_annotation(x=4,y=4,text="Text annotation without arrow",showarrow=False,yshift=10)fig.update_layout(showlegend=False)fig.show()
If the x or y positions of an annotation reference a log axis, you need to provide that position as a log10 value when adding the annotation. In this example, the yaxis is a log axis so we pass the log10 value of 1000 to the annotation's y position.
You can also configure a font's variant, style, and weight on textfont. Here, we configure an italic style on the first bar, bold weight on the second, and small-caps as the font variant on the third.
In the previous example, we set a font weight using a keyword value. You can also set font weight using a numeric value.
The font weights that are available depend on the font family that is set. If you set a font weight that isn't available for a particular font family, the weight will be rounded to the nearest available value.
scattergl traces do not support all numeric font weights. When you specify a numeric font weight on scattergl, weights up to 500 are mapped to the keyword font weight "normal", while weights above 500 are mapped to "bold".
You can configure text case using the textfont.textcase property. In this example, we set textfont.textcase="upper" to transform the text on all bars to uppercase.
In [14]:
importplotly.graph_objectsasgofromplotlyimportdatadf=data.gapminder()grouped=df[df.year==2007].loc[df[df.year==2007].groupby('continent')['lifeExp'].idxmax()]fig=go.Figure(data=go.Bar(x=grouped['lifeExp'],y=grouped['continent'],text=grouped['country'],orientation='h',textfont=dict(family="sans serif",size=14,# Here we set textcase to "upper.# Set to lower" for lowercase text, or "word caps" to capitalize the first letter of each wordtextcase="upper")),layout=go.Layout(title_text='Country with Highest Life Expectancy per Continent, 2007',yaxis=dict(showticklabels=False)))fig.show()
You can add decoration lines to text using the textfont.lineposition property. This property accepts "under", "over", and "through", or a combination of these separated by a +.
In [15]:
importplotly.graph_objectsasgofromplotlyimportdatadf=data.gapminder()grouped=df[df.year==2002].loc[df[df.year==2002].groupby('continent')['lifeExp'].idxmax()]fig=go.Figure(data=go.Bar(x=grouped['lifeExp'],y=grouped['continent'],text=grouped['country'],orientation='h',marker_color='MediumSlateBlue',textfont=dict(lineposition="under"# combine different line positions with a "+" to add more than one: "under+over")),layout=go.Layout(title_text='Country with Highest Life Expectancy per Continent, 2002',yaxis=dict(showticklabels=False)))fig.show()
You can apply a shadow effect to text using the textfont.shadow property. This property accepts shadow specifications in the same format as the text-shadow CSS property.
In [16]:
importplotly.graph_objectsasgofromplotlyimportdatadf=data.gapminder()grouped=df[df.year==1997].loc[df[df.year==1997].groupby('continent')['lifeExp'].idxmax()]fig=go.Figure(data=go.Bar(x=grouped['lifeExp'],y=grouped['continent'],text=grouped['country'],orientation='h',textfont=dict(shadow="1px 1px 2px pink")),layout=go.Layout(title_text='Country with Highest Life Expectancy per Continent, 1997',yaxis=dict(showticklabels=False)))fig.show()
The text attribute supports the following HTML tags: <br>,<b>,<a>, <em>, <sup> and <span>.
In version 5.23 and later, <s> and <u>are also supported.
In [19]:
importplotly.graph_objectsasgofig=go.Figure(data=[go.Scatter(x=[0,1,2,3,4,5,6,7,8],y=[0,1,3,2,4,3,4,6,5],mode="lines+markers",name="Series 1",),go.Scatter(x=[0,1,2,3,4,5,6,7,8],y=[0,4,5,1,2,2,3,4,2],mode="lines+markers",name="Series 2",),],layout=go.Layout(annotations=[dict(x=2,y=5,text="Text annotation using <b>bolded text</b>, <i>italicized text</i>, <u>underlined text</u>, <br>and a new line",showarrow=True,arrowhead=1,),dict(x=4,y=4,text="Text annotation with <a href='https://dash.plotly.com'>a link</a>.",showarrow=False,yshift=10,),],showlegend=False,),)fig.show()
By default, text annotations have xref and yref set to "x" and "y", respectively, meaning that their x/y coordinates are with respect to the axes of the plot. This means that panning the plot will cause the annotations to move. Setting xref and/or yref to "paper" will cause the x and y attributes to be interpreted in paper coordinates.
Try panning or zooming in the following figure:
In [20]:
importplotly.expressaspxfig=px.scatter(x=[1,2,3],y=[1,2,3],title="Try panning or zooming!")fig.add_annotation(text="Absolutely-positioned annotation",xref="paper",yref="paper",x=0.3,y=0.3,showarrow=False)fig.show()
To place annotations relative to the length or height of an axis, the string
' domain' can be added after the axis reference in the xref or yref fields.
For example:
In [21]:
importplotly.expressaspximportplotly.graph_objectsasgodf=px.data.wind()fig=px.scatter(df,y="frequency")# Set a custom domain to see how the ' domain' string changes the behaviourfig.update_layout(xaxis=dict(domain=[0,0.5]),yaxis=dict(domain=[0.25,0.75]))fig.add_annotation(xref="x domain",yref="y domain",# The arrow head will be 25% along the x axis, starting from the leftx=0.25,# The arrow head will be 40% along the y axis, starting from the bottomy=0.4,text="An annotation referencing the axes",arrowhead=2,)fig.show()
The text coordinates / dimensions of the arrow can be specified absolutely, as
long as they use exactly the same coordinate system as the arrowhead. For
example:
In [22]:
importplotly.expressaspximportplotly.graph_objectsasgodf=px.data.wind()fig=px.scatter(df,y="frequency")fig.update_layout(xaxis=dict(domain=[0,0.5]),yaxis=dict(domain=[0.25,0.75]))fig.add_annotation(xref="x domain",yref="y",x=0.75,y=1,text="An annotation whose text and arrowhead reference the axes and the data",# If axref is exactly the same as xref, then the text's position is# absolute and specified in the same coordinates as xref.axref="x domain",# The same is the case for yref and ayref, but here the coordinates are data# coordinatesayref="y",ax=0.5,ay=2,arrowhead=2,)fig.show()
Specifying Source Lines or Figure Notes on the Bottom of a Figure¶
This example shows how to add a note about the data source or interpretation at the bottom of the figure. This example aligns the note in the bottom right corner using the title element and container coordinates and then uses an annotation to add a figure title. A near zero container coordinate is an easy and robust way to put text -- such as a source line or figure note -- at the bottom of a figure. It is easier to specify the bottom of the figure in container coordinates than using paper coordinates, since uncertainty about the size of legends and x-axis labels make the paper coordinate of the bottom of the figure uncertain. Making the y container coordinate very slightly positive avoids cutting off the descending strokes of letters like y, p, and q. Only the title command supports container coordinates, so this example re-purposes the title element to insert the note and re-purposes an annotation element for the title. The top of the figure is typically less cluttered and more predictable than the bottom of the figure, so an annotation with its bottom at a paper y-coordinate slightly greater than 1 is a reasonable title location on many graphs.
In [23]:
importplotly.expressaspxdf=px.data.iris()fig=px.scatter(df,x="sepal_width",y="sepal_length",color="species",size='petal_length',hover_data=['petal_width'])fig.update_layout(title=dict(text="Note: this is the Plotly title element.",# keeping this title string short avoids getting the text cut off in small windows# if you need longer text, consider 1) embedding your graphic on a web page and# putting the note in the HTML to use the browser's automated word wrap,# 2) using this approach and also specifying a graph width that shows the whole title,# or 3) using <BR> tags to wrap the text onto multiple linesyref="container",y=0.005,# The "paper" x-coordinates lets us align this with either the right or left# edge of the plot region.# The code to align this flush with the right edge of the plot area is# predictable and simple.# Putting the title in the lower left corner, aligned with the left edge of the axis labeling would# require graph specific coordinate adjustments.xref="paper",xanchor="right",x=1,font=dict(size=12)),plot_bgcolor="white",# We move the legend out of the right margin so the right-aligned note is# flush with the right most element of the graph.# Here we put the legend in a corner of the graph region# because it has consistent coordinates at all screen resolutions.legend=dict(yanchor="top",y=1,xanchor="right",x=1,borderwidth=1))# Insert a title by repurposing an annotationfig.add_annotation(yref="paper",yanchor="bottom",y=1.025,# y = 1 is the top of the plot area; the top is typically uncluttered, so placing# the bottom of the title slightly above the graph region works on a wide variety of graphstext="This title is a Plotly annotation",# Center the title horizontally over the plot areaxref="paper",xanchor="center",x=0.5,showarrow=False,font=dict(size=18))fig.show()
To show an arbitrary text in your chart you can use texttemplate, which is a template string used for rendering the information, and will override textinfo.
This template string can include variables in %{variable} format, numbers in d3-format's syntax, and date in d3-time-format's syntax.
texttemplate customizes the text that appears on your plot vs. hovertemplate that customizes the tooltip text.
In [24]:
importplotly.graph_objectsasgofig=go.Figure(go.Pie(values=[40000000,20000000,30000000,10000000],labels=["Wages","Operating expenses","Cost of sales","Insurance"],texttemplate="%{label}: %{value:$,s} <br>(%{percent})",textposition="inside"))fig.show()
The following example shows how to show date by setting axis.type in funnel charts.
As you can see textinfo and texttemplate have the same functionality when you want to determine 'just' the trace information on the graph.
Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
Everywhere in this page that you see fig.show(), you can display the same figure in a Dash application by passing it to the figure argument of the Graph component from the built-in dash_core_components package like this:
importplotly.graph_objectsasgo# or plotly.express as pxfig=go.Figure()# or any Plotly Express function e.g. px.bar(...)# fig.add_trace( ... )# fig.update_layout( ... )fromdashimportDash,dcc,htmlapp=Dash()app.layout=html.Div([dcc.Graph(figure=fig)])app.run(debug=True,use_reloader=False)# Turn off reloader if inside Jupyter
You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.