Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python avoid multiple if statement in assigning and plotting colors based on different conditions

Tags:

python

I am assigning different colors for different objects in a dictionary and plotting using pyplot. I used multiple if statements but I wish to avoid doing that. what will be the best way to achieve the plots. Here is my code:

for x,y in data.items():
    if x == 'coupe':
        plt.plot(y, ':', color = "yellow")
    if x == 'bike':
        plt.plot(y, ':', color = "black")
    if x == 'truck':
        plt.plot(y, ':', color = "blue")
    if x == 'van':
        plt.plot(y, ':', color = "white")
    if x == 'sedan':
        plt.plot(y, ':', color = "grey")

I get my desired result but I just know there would be a better way to achieve this. Thank you

like image 396
Starter Avatar asked Sep 25 '26 12:09

Starter


1 Answers

Since all the if statements relate a testing string to an input value to plt.plot, we can use a dictionary to store these pairs, and then write the code more neatly:

d = {'coupe':'yellow',
     'bike':'black',
     ...}
for x,y in data.items():
    if x in d:
        plt.plot(y, ':', color=d[x])
like image 71
Joe Iddon Avatar answered Sep 27 '26 00:09

Joe Iddon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!