Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib annotate doesn't work on log scale?

I am making log-log plots for different data sets and need to include the best fit line equation. I know where in the plot I should place the equation, but since the data sets have very different values, I'd like to use relative coordinates in the annotation. (Otherwise, the annotation would move for every data set.)

I am aware of the annotate() function of matplotlib, and I know that I can use textcoords='axes fraction' to enable relative coordinates. When I plot my data on the regular scale, it works. But then I change at least one of the scales to log and the annotation disappears. I get no error message.

Here's my code:

plt.clf()
samplevalues = [100,1000,5000,10^4]
ax = plt.subplot(111)
ax.plot(samplevalues,samplevalues,'o',color='black')
ax.annotate('hi',(0.5,0.5), textcoords='axes fraction')
ax.set_xscale('log')
ax.set_yscale('log')
plt.show()

If I comment out ax.set_xcale('log') and ax.set_ycale('log'), the annotation appears right in the middle of the plot (where it should be). Otherwise, it doesn't appear.

Thanks in advance for your help!

like image 821
irene Avatar asked Jan 15 '14 14:01

irene


1 Answers

It may really be a bug as pointed out by @tcaswell in the comment but a workaround is to use text() in axis coords:

plt.clf()
samplevalues = [100,1000,5000,10^4]
ax = plt.subplot(111)
ax.loglog(samplevalues,samplevalues,'o',color='black')
ax.text(0.5, 0.5,'hi',transform=ax.transAxes)
plt.show()

Another approach is to use figtext() but that is more cumbersome to use if there are already several plots (panels).

By the way, in the code above, I plotted the data using log-log scale directly. That is, instead of:

ax.plot(samplevalues,samplevalues,'o',color='black')
ax.set_xscale('log')
ax.set_yscale('log')

I did:

ax.loglog(samplevalues,samplevalues,'o',color='black')
like image 133
Christian Alis Avatar answered Sep 24 '22 03:09

Christian Alis