matplotlibscatter-plothorizontal-line

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 ='--')

Here is how it should look like: enter image description here


Solution

  • You can use list comprehension:

    [ax.axhline(y=i, linestyle='--') for i in [150,100,200,300]]