Python Plotly – How to manually set the color of points in a scatter plot?


Plotly is an open-source plotting library in Python that can generate several different types of interactive web-based charts. Plotly can also be used in static document publishing and desktop editors such as PyCharm and Spyder.

In this tutorial, we will see how to manually set the color of points in a scatter plot using Plotly. We will use the plotly.express module to generate scatter plots and then use the update_traces() method to set the desired color plot.

Follow the steps given below to manually set the color of points in a Scatter plot.

Step 1

Import the plotly.express module and alias as px. Then, import the Pandas module and alias as pd.

import plotly.express as px
import pandas as pd

Step 2

Create a dataframe using the following values −

data = {
   'id':[1,2,3,4,5],
   'Age':[21,22,23,24,25]
}
df = pd.DataFrame(data)

Step 3

Create a scatter plot with the X and Y coordinates.

fig = px.scatter(df, x="id", y="Age")

Step 4

Use the update_traces() method to set the color of the traces.

fig.update_traces(marker=dict(color='red'))

Example

The complete code is as follows.

import plotly.express as px import pandas as pd data = { 'id':[1,2,3,4,5], 'Age':[21,22,23,24,25] } df = pd.DataFrame(data) fig = px.scatter(df, x="id", y="Age") fig.update_traces(marker=dict(color='red')) fig.update_layout(width=716, height=400) fig.show()

Output

It will show the following output on the browser −

You can also use the RGB code or the Hex code of "Red" to get the same effect −

# RGB code of Red color
fig.update_traces(marker=dict(color='rgb(255, 0, 0)'))

# Hex code of Red color
fig.update_traces(marker=dict(color='#FF0000'))

Updated on: 21-Oct-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements