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
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With