2

Here is an example of a scatter plot with high 2D point density, just for illustration.

How can I reduce the size of the markers to better distinguish the individual points? The size of the plot should remain as it is.

import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
from matplotlib import cm

np.random.seed(10)

n=3000

x = np.arange(n)
z = np.sin(x/n)
y = np.random.randint(0, 100, size=(n))

colvals = preprocessing.minmax_scale(z)

plt.scatter(x, y, color=cm.rainbow(colvals), marker='.')
plt.xlabel('x')
plt.ylabel('y')

plt.show()

enter image description here

2
  • 1
    @tdy I am wrong, what I said. That is the solution. Thank you very much. You can write this as an answer and I will mark it as solved. It seems that s has no lower boundary?
    – len
    Commented Mar 18, 2022 at 22:22
  • No problem. Any float is valid (even negative values will only give a warning), so the practical lower bound is just whatever is perceptible to the eye for a given figure.
    – tdy
    Commented Mar 18, 2022 at 22:58

1 Answer 1

5

plt.scatter has a parameter s for controlling the marker size.

  • s can either be a single float that applies to all points, e.g. all size 5:

    s = 5
    plt.scatter(x, y, color=cm.viridis(colvals), marker='.', s=s)
    

  • Or s can be an array of sizes that maps to every point, e.g. size 5 when z > 0.5 and size 30 otherwise:

    s = np.where(z > 0.5, 5, 30)
    plt.scatter(x, y, color=cm.viridis(colvals), marker='.', s=s)
    


Note that to match the size of scatter and plot markers, the plot marker's markersize should be the square root of the scatter marker's s:

s = 900

plt.scatter(-1, 0, s=s, color='tab:orange')
plt.plot(1, 0, 'o', markersize=s ** 0.5)

2
  • Side note: I swapped out rainbow for viridis since the rainbow colormap should be avoided when possible.
    – tdy
    Commented Mar 19, 2022 at 0:02
  • 1
    Thanks for the link to the interesting paper, many researchers still use rainbow or monochrome color maps with increasing brightness.
    – len
    Commented Mar 21, 2022 at 7:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.