Calibration of a gas sensor using data from a graph

Newbie here.

I currently have a gas sensor connected to a raspberry pi. The sensor reading, however, is affected by temperature. I’d like to account for the change in order to get a more accurate reading. The manufacturer of the gas sensor has a graph which shows the temperature-dependent variation (attached below). I have a DH22 temperature sensor, and at first thought of just using a case statement or a bunch of IF statements to do the calibration, but I was wondering if there isn’t a better way of going about this?

The graph is non-linear which makes it a bit trickier. Thanks for your help.

Do you have the polynomial for the fitted function? If so, just use that to calculate the correction.

If you only have the point data, then interpolate on that. Here’s a super simplistic (untested :grin:) 3-point example that should give you some ideas:

def correction(temp):
    X = -40.00,  0.00, 40.00
    Y =  -0.61, -0.41,  0.78
    for x, y in zip(X, Y):
        if temp < x: continue
        return y
    return 0.0  # Out of range.

You could try a log-log plot, i.e. if you have y=f(x) then plot log(y) vs log(x). This should make the plot a straight line. You can calculate the best fit for that straight line.

Adding a few datapoints estimated by eye, to the calculator on this site yields this info:

Fitted coefficients:
a = -0.3998
b = 0.01712
c = 0.0003258
• Quadratic model:
y = -0.3998 + 0.01712x + 0.0003258x2
• Coefficient of determination R²:
R²= 0.9961

This leads to a function something like:

def correction(temp: float) -> float:
    delta = -0.3998 + 0.01712 * temp + 0.0003258 * temp * temp
    return temp + delta

Details on my fit-by-eye

for t in range(-40, 60, 10):
    print(f"{t = :+3} delta = {correction(t) - t:+4.2f}")

_printed = '''
t = -40 delta = -0.56
t = -30 delta = -0.62
t = -20 delta = -0.61
t = -10 delta = -0.54
t =  +0 delta = -0.40
t = +10 delta = -0.20
t = +20 delta = +0.07
t = +30 delta = +0.41
t = +40 delta = +0.81
t = +50 delta = +1.27
'''