Search code examples
pythonmatplotlibtwinx

In matplotlib, pyplot.text disappears when applying twinx. How can it appear?


plt.text(x, y, text) is working when I use single y-axis but it disappears when I apply twinx. Can it be fixed?

fig, ax = plt.figure(figsize=(8,6))
text = "E_rms(test) = {:7.3f}/nE_maxres = {:7.3f}".format(rmse,maxres)
plt.text(0,0,text)

plt.xlabel('data')
ax.set_ylable('PE(eV)')
ax.tick_params(axis='y', labelcolor='b')
if Ltwinx:
    ax2 = ax.twinx()
    ax2.set_ylabel("Difference(eV)")
    ax2.set_tick_params(axis='y', labelcolor='g')

p1 = ax.scatter(range(y), y, c='r', label='true')
p2 = ax.scatter(range(y), h, c='b', label='hypothesis')
if Ltwinx:
    p3, = ax2.plot(range(y), diff, c='g', label='difference')
    plt.legend([p1,p2],['true value', 'hypothesis'],loc=(0.0, 0.1))
else:
    p3, = plt.plot(range(y), diff, c='g', label='difference')
    plt.legend([p1,p2,p3],['true value', 'hypothesis', 'difference'],loc=(0.0, 0.1))
plt.show()

This code is an extraction from full code and the belows are figure with two y-axes (1st figure) and single y-axis, where text disappeared in twinx (1st figure). Note y-axis scale is different due to the values of "diff" though p1, p2 figures are same in both figures.

plot with twinx plot with single y-axis


Solution

  • I have misunderstood the manual for matplotlib.pyplot.text. To use axis coordinate such as (0,0) to (1,1) regardless of y-values, I should add keyword of "transform=ax.transAxes". So

    plt.text(0,0,text, transform=ax.transAxes)
    

    is working.