Question

I want a scatterplot with values exceeding a particular threshold to have another color then the ones "inside" the threshold.

Here is what I wrote so far:

import numpy as np
import numpy.random as rnd
import matplotlib.pyplot as plt

n  = 100
x  = rnd.uniform(low  = -1,  high = 1, size = n)
y  = rnd.uniform(low  = -1,  high = 1, size = n)

a  = x**2 + y**2
c  = np.zeros(n) 

for i in range(n):
    if a[i] <= 1:
        c[i]  = 0
    else:
        c[i]  = 1

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

the output is a completely black scatter plot.

c = array([ 0.,  0.,  0.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
    1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
    0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,
    0.,  0.,  0.,  0.,  0.,  1.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,
    0.,  1.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
    0.,  0.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,
    1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
    0.,  0.,  1.,  1.,  0.,  0.,  1.,  1.,  1.])

I tried the following:

for i in range(n):
if a[i] <= 1:
    c[i]  = "r"
else:
    c[i]  = "g"
ValueError: could not convert string to float: r

and several other variations of the theme. However I am stuck. Please help, thank you very much for your time.

Best wishes

Was it helpful?

Solution

You have c defined as integers with this line:

c  = np.zeros(n)

But then in your second code snippet you are trying to set c as a string.

c[i]  = "r"

Choose a new name for your string array:

cs = []
for i in range(n):
    if a[i] <= 1:
        cs.append("r")
    else:
        cs.append("g")

If scatter complains about c not being from numpy, you can set a numpy chararry with: numpy.chararray.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top