I want to create a contour plot of the log-likelihood of a Gaussian sample with OpenTURNS. Each contour maps to a function value, which is indicated by the legend of the plot. The problem is that the legend somewhat hides the contours: how to setup the plot so that the legend does not hide the content?
Here is an example. I create a Normal
distribution corresponding to the height of man with age between 20 and 79 years old (see "Statistical Abstract of the United States U.S. Census Bureau."
Table 209. 2012). Then I generate a sample from this distribution. I define the log-likelihood function, which takes the vector (mu, sigma) on input and returns a one-dimensional vector containing the log-likelihood on output. I can use the draw
method of this function to create the contour plot.
import openturns as ot
import openturns.viewer as otv
mu = 1.763
sigma = 0.0680
N = ot.Normal(mu, sigma)
sample_size = 100
sample = N.getSample(sample_size)
def loglikelihood_gauss(X):
"""Compute the log-likelihood of a Gaussian sample."""
mu, sigma = X
N = ot.Normal(mu, sigma)
log_pdf = N.computeLogPDF(sample)
sample_size = sample.getSize()
log_likelihood = log_pdf.computeMean() * sample_size
return log_likelihood
# Contour plot
logLikelihoodFunction = ot.PythonFunction(2, 1, loglikelihood_gauss)
ot.ResourceMap_SetAsUnsignedInteger("Contour-DefaultLevelsNumber", 5)
graph = logLikelihoodFunction.draw([1.65, 0.04], [1.85, 0.15], [50]*2)
graph.setXTitle(r"$\mu$")
graph.setYTitle(r"$\sigma$")
graph.setTitle("Log-Likelihood.")
view = otv.View(graph)
This produces:
How to setup the plot so that the legend does not hide the contours?
The first trick is to use the
bbox_to_anchor
option of thelegend
matplotlib function. This is possible because all OpenTURNS graphics are from Matplotlib at the Python layer. The second trick is to get the figure from theView
object, based on thegetFigure
method. Without further code, this produces a second legend which is at the correct location, but duplicates the legend. The third trick is to hide the old legend by setting the content to empty strings.When saving the figure, the legend may be cropped. It might be necessary to use the
bbox_inches
option: