0

The texts on the right on this pyplot graph are clipped, how can I expand the plot area without changing the x-axis?

Minimal example code (similar to but not identical to example image)

import numpy as np

import matplotlib.pyplot as plt
import matplotlib as mp

n40=146-1.07*40
n90=146-1.07*90 
ageAxis =np.array([10, 40, 90])
Normal=np.array([n40, n40, n90])
plt.plot(ageAxis,Normal)

plt.text(90.2,50,'long text here that will be clipped')
ax = plt.gca()
ax.set_ylim([0,165])
ax.set_xlim([0,90])
fig= plt.gcf()
# set size fig.set_size_inches(20, 10.5)
plt.show()

pyplot

Stefan
  • 622
  • 1
  • 5
  • 17
  • 1
    fig = matplotlib.pyplot.gcf() fig.set_size_inches(18.5, 10.5) try this and see whether it works or not. – Ishtiaque05 Feb 06 '19 at 08:21
  • @Ishtiaque05 well, that will set the physical size of the plot, but the text should be visible no matter the scaling of the plot. – Stefan Feb 06 '19 at 08:25
  • 1
    If you just want to save the figure with all the text visible, you could go for `fig.save_fig(bbox_inches='tight')`. For interactive plots you can use `fig.tight_layout()`, but note that once you resize the figure, `tight_layout` needs to be called again. See [here](https://stackoverflow.com/a/47838687/2454357) for a solution. – Thomas Kühn Feb 06 '19 at 08:32
  • Sorry there was a typo, it's `fig.savefig(bbox_inches='tight')`, i.e. one less underscore. – Thomas Kühn Feb 06 '19 at 08:45

1 Answers1

1

It seems that it can be done with a combination of set_size_inches and subplots_adjust

Not elegant, I think, but it works:

import numpy as np

import matplotlib.pyplot as plt
import matplotlib as mp

n40=146-1.07*40
n90=146-1.07*90 
ageAxis =np.array([10, 40, 90])
Normal=np.array([n40, n40, n90])
plt.plot(ageAxis,Normal)

plt.text(90.2,50,'long text here that will be clipped')
ax = plt.gca()
ax.set_ylim([0,165])
ax.set_xlim([0,90])
fig= plt.gcf()
fig.set_size_inches(10, 5.5)     # set a suitable size
plt.subplots_adjust(right=0.75)  # adjust plot area
plt.show()
Stefan
  • 622
  • 1
  • 5
  • 17