2

How to manually set the strings to color when using the matplotlib plot figures?

For example, I have the following dataset.

# Generate data...
import pandas as pd   
seed(1)
df = pd.DataFrame({
        'x':np.random.random(10),
        'y':np.random.random(10),
        'z':np.random.choice(['yes','no'], 10)
    })

df
          x         y    z
0  0.417022  0.419195   no
1  0.720324  0.685220   no
2  0.000114  0.204452   no
3  0.302333  0.878117   no
4  0.146756  0.027388   no
5  0.092339  0.670468   no
6  0.186260  0.417305  yes
7  0.345561  0.558690   no
8  0.396767  0.140387   no
9  0.538817  0.198101  yes

I want to plot 'yes' as 'red' and 'no' as 'blue' with following code, but how can I set the colors?

# Plot...
plt.scatter(df.x, df.y, c= df.z) 

1 Answer 1

2

I think this line will do what You want:

plt.scatter(df.x, df.y, c=['red' if x == 'yes' else 'blue' for x in df.z])
Sign up to request clarification or add additional context in comments.

Comments

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.