Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to add multiple text labels from DataFrame columns in Python Plotly?
Plotly is a powerful Python library for creating interactive visualizations. You can add multiple text labels from DataFrame columns to enhance your charts with additional information that appears on hover or as annotations.
In this tutorial, we'll learn how to create a scatter plot with text labels from different DataFrame columns using Plotly's graph_objects module.
Required Libraries
We'll use the following Python libraries ?
plotly.graph_objects For creating interactive plots
pandas For DataFrame operations
plotly.offline For generating HTML output
Creating the DataFrame
First, let's create a sample DataFrame with student data ?
import pandas as pd
import plotly.graph_objs as go
import plotly.offline as py
# Create sample DataFrame
df = pd.DataFrame({
'Age': [20, 22, 23, 24, 21],
'Mark': [80, 85, 90, 95, 99],
}, index=['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'])
# Set index name
df.index.name = 'Student'
# Sort by Age for better visualization
df = df.sort_values('Age')
print(df)
Age Mark
Student
Alice 20 80
Eve 21 99
Bob 22 85
Charlie 23 90
Diana 24 95
Adding Text Labels from Multiple Columns
Now we'll create a scatter plot where hover text shows information from multiple DataFrame columns ?
import pandas as pd
import plotly.graph_objs as go
import plotly.offline as py
# Create DataFrame
df = pd.DataFrame({
'Age': [20, 22, 23, 24, 21],
'Mark': [80, 85, 90, 95, 99],
}, index=['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'])
df.index.name = 'Student'
df = df.sort_values('Age')
# Create scatter plot with text labels
trace = go.Scatter(
x=df.index,
y=df['Mark'],
name='Student Marks',
text=df['Age'], # Age values as hover text
hovertemplate='<b>%{x}</b><br>Mark: %{y}<br>Age: %{text}<extra></extra>',
mode='lines+markers+text',
textposition='top center',
line=dict(color='green', width=3),
marker=dict(size=10, color='darkgreen')
)
# Set layout
layout = dict(
title='Student Marks with Age Labels',
xaxis=dict(title='Students'),
yaxis=dict(title='Marks'),
showlegend=True
)
# Create and display the plot
data = [trace]
fig = dict(data=data, layout=layout)
py.offline.plot(fig, filename='student_marks.html')
Advanced Example with Custom Text Labels
For more complex text labels combining multiple columns, you can create custom hover text ?
import pandas as pd
import plotly.graph_objs as go
import plotly.offline as py
# Create DataFrame with more columns
df = pd.DataFrame({
'Age': [20, 22, 23, 24, 21],
'Mark': [80, 85, 90, 95, 99],
'Subject': ['Math', 'Physics', 'Chemistry', 'Biology', 'English']
}, index=['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'])
df.index.name = 'Student'
# Create custom hover text combining multiple columns
df['hover_text'] = df.apply(lambda row: f"Age: {row['Age']}, Subject: {row['Subject']}", axis=1)
trace = go.Scatter(
x=df.index,
y=df['Mark'],
name='Student Performance',
text=df['hover_text'],
hovertemplate='<b>%{x}</b><br>Mark: %{y}<br>%{text}<extra></extra>',
mode='markers+lines',
line=dict(color='blue', width=2),
marker=dict(size=12, color='lightblue', line=dict(color='darkblue', width=2))
)
layout = dict(
title='Student Performance with Multi-Column Labels',
xaxis=dict(title='Students'),
yaxis=dict(title='Marks'),
template='plotly_white'
)
fig = dict(data=[trace], layout=layout)
py.offline.plot(fig, filename='advanced_labels.html')
print("Plot saved as 'advanced_labels.html'")
Plot saved as 'advanced_labels.html'
Key Parameters for Text Labels
| Parameter | Description | Example |
|---|---|---|
text |
Text to display on hover/annotation | df['Age'] |
hovertemplate |
Custom hover text format | '%{x}: %{text}' |
textposition |
Position of text labels | 'top center' |
mode |
Display mode | 'markers+lines+text' |
Conclusion
Adding multiple text labels from DataFrame columns in Plotly enhances data visualization by providing additional context on hover or as annotations. Use the text parameter for simple labels or create custom hovertemplate for complex multi-column information display.
