Adding the minimal temperature difference between two lines in python plot

47 views Asked by At

In my Python plot, I want to determine the largest and smallest temperature difference between two lines in y-direction with accessory x-value. My code is as follows;

# IMPORT MODULES
import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
import datetime
import time
from scipy.signal import find_peaks, peak_prominences
import os

# PARAMETERS
simulationtype = "temperature"
filename = "v22plot_"+simulationtype+"curve.txt" # VARIABLE
setTemp = 210

# LOAD DATA AND CREATE COLUMNS
df = pd.read_csv(filename, delim_whitespace=True,skiprows=4, encoding='latin1')
x1 = df.iloc[:,0]
y1 = df.iloc[:,1]
x2 = df.iloc[:,2]
y2 = df.iloc[:,3]
x3 = df.iloc[:,4]
y3 = df.iloc[:,5]

# CREATE PLOT
fig1 = plt.gcf()
plt.axhline(y = setTemp, color = '0.5', linestyle = '--') 
plt.plot(x1, y1, '*--', linewidth=2, markersize=3, label="Insert_TC")
plt.plot(x2, y2, '*--', linewidth=2, markersize=3, label="MS_TC")
plt.plot(x3, y3, '*--', linewidth=2, markersize=3, label="FS_TC")

xfill = np.sort(np.concatenate([x2, x3]))
y1fill = np.interp(xfill, x2, y2)
y2fill = np.interp(xfill, x3, y3)
plt.fill_between(xfill, y1fill, y2fill, where=y1fill < y2fill, interpolate=True, color='dodgerblue', alpha=0.2)
plt.fill_between(xfill, y1fill, y2fill, where=y1fill > y2fill, interpolate=True, color='crimson', alpha=0.2)
plt.grid('on', color='grey', linestyle='-', linewidth=0.25)

plottitle = 'Temperature'
plt.title(plottitle)

plt.xlabel('Time [s]')
plt.ylabel('Temperature [°C]')
plt.legend(loc='upper center', ncol=1,bbox_to_anchor=(1.1, 1.), fancybox=True, shadow=True, fontsize="8")

# GENERATE PLOTNAME
timestr = time.strftime("%Y%m%d")
plotname = timestr + "_" + plottitle

# SAVE PLOT
plt.savefig(plotname, dpi= 300, bbox_inches='tight')
plt.show()

This results in the following graph: Graph

However, I want to add the values and location of lowest and largest delta T between two lines to be in my plot. The picture below visualizes what I mean; enter image description here

I am not sure how to handle this. Can someone lead me in the right direction? Thank you in advance.

1

There are 1 answers

0
mozway On

You could identify the position of the min/max difference with argmin/argmax of the difference between y2fill and y1fill, then use vlines and annotate:

diff = y2fill-y1fill

min_idx = np.argmin(diff)
max_idx = np.argmax(diff)

plt.vlines(xfill[min_idx], y1fill[min_idx], y2fill[min_idx],
           color='k', ls='--')
plt.annotate(f'ΔTmin = {diff[min_idx]:.1f}°C',
             (xfill[min_idx], y1fill[min_idx]),
             xytext=(0, -5), textcoords='offset points',
             ha='center', va='top'
            )

plt.vlines(xfill[max_idx], y1fill[max_idx], y2fill[max_idx],
           color='k', ls='--')
plt.annotate(f'ΔTmax = {diff[max_idx]:.1f}°C',
             (xfill[max_idx], y1fill[max_idx]),
             xytext=(0, -5), textcoords='offset points',
             ha='center', va='top'
            )

Output:

matplotlib vertical line min max difference between two curves

Dummy input:

import pandas as pd
import numpy as np

xs = np.linspace(2500, 2620, 200)
df = pd.DataFrame(dict(enumerate([xs, np.sin(xs/30)*5+210,
                                  xs, np.sin(xs/30-4)+210,
                                  xs, np.sin(xs/25-5)+220,])))