Using Text
Adding titles and captions to a Plotly visualization enhances its clarity and provides context to the audience. In Plotly, you can customize the main title, axis titles, and even add annotations to serve as captions or additional descriptions.
Adding Titles and Captions in Plotly
Example: Adding a Main Title and Axis Titles
import plotly.express as px
# Sample data
data = {
'Category': ['A', 'B', 'C', 'D'],
'Values': [10, 20, 15, 25]
}
df = pd.DataFrame(data)
# Create a bar chart with titles
fig = px.bar(df, x='Category', y='Values', title='Main Title: Category vs. Values')
fig.update_layout(
xaxis_title='Categories', # X-axis title
yaxis_title='Values', # Y-axis title
title_font=dict(size=24), # Customize title font size
)
fig.show()
Example: Adding Annotations
In Plotly Express, you can add annotations by updating the layout of the figure with fig.update_layout()
and using the annotations
parameter. This allows you to place text or symbols on the chart to provide additional information or context.
import pandas as pd
import plotly.express as px
# Sample data
data = {
'Category': ['A', 'B', 'C', 'D'],
'Values': [10, 20, 15, 25]
}
df = pd.DataFrame(data)
# Create a bar chart
fig = px.bar(df, x='Category', y='Values', title='Bar Chart with Annotations')
# Add annotations
fig.update_layout(
annotations=[
dict(
x='B', # X-coordinate of the annotation
y=20, # Y-coordinate of the annotation
text='Highest Value', # Text of the annotation
showarrow=True, # Show an arrow pointing to the coordinate
arrowhead=2, # Arrow style
ax=0, ay=-40, # Offset for the arrow
font=dict(size=12, color='black'), # Font size and color
align='center'
),
dict(
x='D',
y=25,
text='Second Highest',
showarrow=False, # No arrow for this annotation
font=dict(size=12, color='blue')
)
]
)
# Show the plot
fig.show()
Key Parameters in annotations
:
annotations
:x
andy
: The coordinates where the annotation appears.text
: The text content of the annotation.showarrow
: Whether to display an arrow pointing to the annotation.arrowhead
: The style of the arrow (ifshowarrow=True
).ax
anday
: The offsets for the arrow relative to the annotation text.font
: Dictionary specifying the font size, color, and style.align
: Text alignment, such as 'center', 'left', or 'right'.
Notes:
The
x
andy
values in annotations align with the data values in the chart.You can combine multiple annotations in a list to annotate different parts of the chart.
For more information, go to the Plotly documentation: https://plotly.com/python/tick-formatting/. More details on specific formats are here: https://github.com/d3/d3-format/blob/master/README.md#locale_format.
Last updated