Customize with matplotlib

In this example, we will see how to modify the matplotlib figures generated by a DatasetPlot. This can be useful to finely tune a graph for a presentation or a paper.

from __future__ import annotations

from matplotlib import pyplot as plt

from gemseo.datasets.dataset import Dataset
from import YvsX

First, we build a simple Dataset containing a cloud of points ((1, 1), (2, 0), (3, 1)) of the tuple ("a", "b").

dataset = Dataset()
dataset.add_variable("a", [[1], [2], [3]])
dataset.add_variable("b", [[1], [0], [1]])

Then, we define a YvsX chart, which is a particular DatasetPlot:

yvsx = YvsX(dataset, "a", "b")

and draw the figure.

figures = yvsx.execute(save=False)

By default, the horizontal and vertical labels are the names of the variables, namely "a" and "b" in this example. As these labels are not so relevant, we are going to modify this figure directly with matplotlib instead of saving it. For that, we get the matplotlib Axes of the matplotlib Figure:

figure = figures[0]
ax = figure.axes[0]

and change the labels:

ax.set_xlabel("A relevant x-label")
ax.set_ylabel("A relevant y-label")

We can also add a grid:


Lastly, we can save the figure with matplotlib


and display it:

Note that in this pedagogical example, we modified basic properties of the chart which could have been modified with the attributes of DatasetPlot, e.g. yvsx.xlabel = "A relevant x-label". But it is impossible to add attributes or methods for all the features of matplotlib. It is therefore advisable to check if an attribute of DatasetPlot can help and if not, access and modify the matplotlib Figure as shown here.

Gallery generated by Sphinx-Gallery