'Is there a way to plot multiple horizontal lines using hlines() function in a single plot of matplotlib?
I have an pm2_5 dataframe data which I've plotted using a matplotlib scatterplot
.
I want to insert multiple horizontal lines at different y-values,
I'm doing it by manually calling the '''ax.axhline''' function for each different value of y. Is there any way to automate the whole process?
# making a graph with delineated health levels of pm2.5 in the year 2015
fig, ax=plt.subplots(figsize=(10,7));
pm2_5.plot(kind='scatter',x='S_no',y='pm2_5',c='pm2_5',ax=ax, cmap='tab20b');
ax.axhline(y=150,linestyle ='--')
ax.axhline(y=100,linestyle ='--')
ax.axhline(y=200,linestyle ='--')
ax.axhline(y=300,linestyle ='--')
Solution 1:[1]
You can use list comprehension:
[ax.axhline(y=i, linestyle='--') for i in [150,100,200,300]]
Solution 2:[2]
Correcting the above answer to remove the spelling mistake...
[ax.axhline(y=i, linestyle='--') for i in [150,100,200,300]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Jack Ballinger |