0

How to place text above hatched zone using matplotlib? An example is shown below. enter image description here Below are my sample code for easy understanding

from pylab import *
fig=figure()
x=array([0,1])
yc=array([0.55,0.48])


yhc=array([0.55,0.68])

yagg=array([0.45,0.48])

plot(x,yc,'k-',linewidth=1.5)
plot(x,yhc,'k-',linewidth=1.5)
plot(x,yagg,'k-',linewidth=1.5)

xticks(fontsize = 22)
yticks(fontsize = 22)
ylim(0,1)
ax=axes()


p=fill_between(x, yc, yhc,color="none")

from matplotlib.patches import PathPatch 
for path in p.get_paths(): 
    p1 = PathPatch(path, fc="none", hatch="/") 
    ax.add_patch(p1) 
    p1.set_zorder(p.get_zorder()-0.1) 

props = dict(boxstyle='round',facecolor='white', alpha=1,frameon='false')
text(0.6, 0.55, 'hi',fontsize=22)
fig.savefig('vp.png', transparent=True,bbox_inches='tight')

enter image description here

The hatched zone really makes it hard to see the text.

user3737702
  • 591
  • 1
  • 10
  • 17

1 Answers1

1

You can give the text command a bounding box (bbox) that has its own background. Here's a simple change:

text(0.6, 0.55, 'hi',fontsize=22, bbox=dict(facecolor='white', alpha=0.9, ))

which alters your example plot like so:

enter image description here

if you look up bboxes, you can figure out how to turn off the border around the bbox, if it conflicts with your hatching. Or make it a roundrec, etc etc. Here's an example of various text-bounding-box styles.

Community
  • 1
  • 1
cphlewis
  • 15,759
  • 4
  • 46
  • 55
  • Thanks, however if you do this way, can you remove the frame of the box? Or there is no choose, you have to accept it? – user3737702 Jun 29 '15 at 23:19
  • `text(0.6, 0.55, 'hi',fontsize=22, bbox=dict(facecolor='white', edgecolor='none', alpha=0.9, )) ` will have no visible frame. – cphlewis Jun 30 '15 at 06:15