Create Matplotlib Scatter with RGB Color – Matplotlib Tutorial

By | September 10, 2021

When we are using matplotlib to plot a scatter, we may want to use rgb color. In this tutorial, we will introduce you how to do.

RGB in matplotlib

As to rgb in matplotlib, for example:

c = [r, g, b]

The value of r, g, b shoud be in 0-1.

How to use rgb color in matplotlib scatter?

We will use an example to show you how to do.

First, we should import matplotlib and create x, y.

# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt

x = [1, 8, 3, 1, 5, 6, 7, 4, 9, 10]
y = [1, 5, 2, 7, 10, 9, 3, 6, 2, 4]

Then we will create a rgb color for each 2d point.

rgb = []
for i in x:
    i = i * 2
    c = [i * 5 / 255, i * 10 /255 , i* 5/ 255]
    rgb.append(c)

In order to create random or hex rgb color in python, you can read this tutorial:

Generate Random RGB and Hex Color in Python: A Step Guide – Python Tutorial

Finally, we can plot this scatter as follows:

plt.scatter(x, y, c = rgb)
plt.show()

Run this code, you will see:

Create Matplotlib Scatter with RGB Color - Matplotlib Tutorial

If you want to create a scatter with labels, you can read this tutorial:

Python Matplotlib Implement a Scatter Plot with Labels: A Completed Guide – Matplotlib Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *