how to add a metric , like mse to agraph in matplotlib in python

To add a metric, such as Mean Squared Error (MSE), to a graph in Matplotlib, you can use the text() function in Matplotlib. Here's some sample code that shows how to do this:

main.py
import matplotlib.pyplot as plt
import numpy as np

# define some data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# compute the mse
mse = ((y - x)**2).mean()

# create the plot
fig, ax = plt.subplots()
ax.plot(x, y)

# add the mse as text to the plot
ax.text(0.05, 0.95, f"MSE: {mse:.3f}", transform=ax.transAxes, fontsize=14,
        verticalalignment='top', bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))

# show the plot
plt.show()
447 chars
21 lines

This code computes the mean squared error between the sine function and the x-axis, and then adds it to the plot as text using the ax.text() function. The transform=ax.transAxes argument ensures that the text is positioned relative to the axes rather than the data; fontsize determines the size of the font; verticalalignment determines where the text is placed vertically; and the bbox argument creates a rectangular box around the text to make it stand out.

gistlibby LogSnag