简体   繁体   中英

matplotlib: draw a box on axes

import matplotlib.patches as patches

df2 = pd.melt(
    data2.query('worktype_id!=38')[['period','worktype', 'utilization_billable', 'utilization' ]], 
    id_vars=['period', 'worktype']).sort_values(['period', 'variable'], ascending=[True, True])
g = sns.relplot(x='period', y='value', 
            hue='variable', data=df2, col='worktype', kind='line', col_wrap=4, 
            )
for ax in g.axes:
    ax.axhline(y=75, color='g', linestyle='--')
    ax.axhline(y=90, color='r', linestyle='--')
    rect = plt.Rectangle((10,10),10,10,linewidth=3,edgecolor='r',facecolor='red', alpha=1)
    ax.add_patch(rect)

I want to draw the box between y=75 and 90 (green and red lines on the chart), but nothing is shown up when I do ax.add_patch

this is the image I get:

在此处输入图片说明

So How do I fill out the area between red and green horizontal lines?

If you have a fixed area you want to fill and you want to do it across the entire chart, you are probably better off using axvspan . Eg

ax.axvspan(75, 90, facecolor='red')
plt.fill_between(plt.xlim(),[75,75],[90,90])
  • plt.xlim() : Returns start and end of xaxis
  • At starting of x axis start filling the color starting from 75 and ending at 90 of y axis
  • Continue filling till the end of x axis again starting from 75 ending at 90 of y axis

You will not need to plot a Rectangle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM