4

(While there are several questions similar to my problem, Almost all of them were related to text-box, legend and annotation.)

Using a loop, I want to show specific information for 32 attributes: Histogram on the left and statistics on the right.

Dealing with just one attribute it's really simple, I set x,y for the text position and that's it:

#Histogram
sns.distplot(n1, kde=True)#fit=stats.beta)
plt.title('Histogram')
plt.xlabel('Duration')
plt.xticks(np.arange(0, max(n1)+1, 0.5))

#Statistics (There are 13 in total)
plt.text(1.85,5,'Standard Time: %6.4f'%(ST.iloc[j,0]))
plt.text(1.85,5,'Median: %6.4f'%(medmed))
plt.text(1.85,4.65,'Variance from ST: %6.2f '%(Totvarval))
plt.text(1.85,4.3,'Standard Deviation: %6.4f'%(np.std(n1)))

The problem is when I create the loop for all the attributes, given the different range of each, the text positions changes relatively causing such a result:

Example for 2 attributes

I know there should be a way to fix the coordination but I couldn't find it in the documentation.

Navid
  • 106
  • 2
  • 6

1 Answers1

5

The coordinates passed to pyplot.text are data coordinates (as the documentation points out). This means that the absolute (pixel) coordinates your text goes at depend on the X and Y ranges of your plot axes. If you want to specify a position relative to the axes themselves rather than the data, you have to convert your coordinates, for example like this:

x0, xmax = plt.xlim()
y0, ymax = plt.ylim()
data_width = xmax - x0
data_height = ymax - y0
plt.text(x0 + data_width * 1.5, y0 + data_height * 0.5, 'Some text')
tjollans
  • 717
  • 4
  • 18
  • 2
    It is far better to use `annotate` and one of the figure or axes units. This lets mpl do that math for you and will stay in the same place if you pan/zoom. – tacaswell May 14 '16 at 20:19
  • Sounds like a good idea. You should write an answer, @tcaswell ! – tjollans May 14 '16 at 20:44