How to highlight a single data point on a scatter plot using plotly express
Asked Answered
N

2

10

In a scatter plot created using px.scatter, how do I mark one data point with a red star?

fig = px.scatter(df, x="sepal_width", y="sepal_length")
# Now set a single data point to color="red", symbol="star".
Nutation answered 8/12, 2021 at 13:13 Comment(0)
D
11

This isn't really highlighting an already existing data point within a trace you've already produced, but rather adding another one with a different visual appearance. But it does exactly what you're looking for:

fig.add_trace(go.Scatter(x=[3.5], y=[6.5], mode = 'markers',
                         marker_symbol = 'star',
                         marker_size = 15))

Plot:

enter image description here

Complete code:

import plotly.express as px
import pandas as pd
import plotly.graph_objects as go
df = px.data.iris() # iris is a pandas DataFrame
fig = px.scatter(df, x="sepal_width", y="sepal_length")
fig.add_trace(go.Scatter(x=[3.5], y=[6.5], mode = 'markers',
                         marker_symbol = 'star',
                         marker_size = 15))
fig.show()
Douglassdougy answered 8/12, 2021 at 13:22 Comment(0)
T
6

This directly modifies the Scatter trace's Marker itself:

import plotly.express as px

# Load data, make figure.
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length")
trace = next(fig.select_traces())

# Set default point styles.
n = len(trace.x)
color = [trace.marker.color] * n
size = [8] * n
symbol = [trace.marker.symbol] * n

# Modify kth point.
k = 136
color[k] = "red"
size[k] = 15
symbol[k] = "star"

# Update trace.
trace.marker.color = color
trace.marker.size = size
trace.marker.symbol = symbol

# Alternatively, call:
# fig.update_traces(marker=dict(color=color, size=size, symbol=symbol))

fig.show()

plot

Trev answered 3/7, 2022 at 3:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.