if slope is greater than some threshold, then color the line red in python

Viewed 193

I have a line graph that I'm plotting in python. The last thing that I need to do is add a line telling it to color a section of the graph red if the slope is greater that 25. How would I do this?

Here's what I have so far.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

data = pd.read_csv('ReactorStartupTemps.csv')
print(data)

plt.rcParams["figure.figsize"] = [5, 4]
plt.rcParams["figure.autolayout"] = True
plt.xlabel('Time [min]', fontdict={'fontname': 'Times New Roman', 
'style': 'italic'})
plt.ylabel('Temperature [C]', fontdict={'fontname': 'Times New Roman', 
'style': 'italic'})
plt.title('Reactor Startup Temperatures', fontdict={'fontname': 'Times 
New Roman', 'style': 'italic'})

[slope, intercept] = np.polyfit(data.Time, data.Temp, 1)
if slope > 25:
    plt.plot(data.Time, data.Temp, color="red", linewidth=1.5)
else:
    plt.plot(data.Time, data.Temp, color="black", linewidth=1.5)

plt.minorticks_on()
plt.grid(which='major', color='grey', linewidth=.8)
plt.grid(which='minor', color='lightgrey', linewidth=.4, ls='--')

plt.show()

What the graph needs to look like:

Graph as of now:

2 Answers
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv('ReactorStartupTemps.csv')
print(data)

plt.rcParams["figure.figsize"] = [7, 5]
plt.rcParams["figure.autolayout"] = True
plt.xlabel('Time [min]', fontdict = {'fontname': 'Times New Roman', 
'style': 'italic'})
plt.ylabel('Temperature [C]', fontdict = {'fontname': 'Times New 
Roman', 
'style': 'italic'})
plt.title('Reactor Startup Temperatures', fontdict = {'fontname': 
'Times 
New Roman', 'style': 'italic'})    
slope, intercept = np.polyfit(np.log(data.Time), np.log(data.Temp), 1)
if slope > 25 :
    plt.plot(data.Time, data.Temp, color = "red",linewidth = 1.5)
else:
    plt.plot(data.Time, data.Temp, color = "black",linewidth = 1.5)
plt.minorticks_on()
plt.grid(which = 'major', color = 'grey', linewidth = .8)
plt.grid(which = 'minor', color = 'lightgrey', linewidth = .4, ls = 
'--')

plt.show()

first you have to calculate slope and then you can implement your condition

for slope calculation

slope, intercept = np.polyfit(np.log(data.Time), np.log(data.Temp), 1)

Currently you are using the slope of the regression line. np.polyfit performs least squares and returns the slope of the fitted line, which is not what you want.

Instead you're looking for the slope between all consecutive points:

  • Use Series.diff to compute (y2-y1) / (x2-x1) for all consecutive points
  • Use Series.where to mask the segments where the slope exceeds 25
  • Use a high zorder to raise the masked segments
THRESHOLD = 25

slopes = data.Temp.diff() / data.Time.diff()
plt.plot(data.Time, data.Temp, color='k')
plt.plot(data.Time, data.Temp.where(slopes > THRESHOLD), color='r', zorder=10)

Related