'I am passing a function through a dataframe in subgroups and I would like to get a separate plot for each subgroup. Now plots overalap
I want to calculate the prediction bands = (upb and lpb) of subgroups in my dataframe and plot each of them individually. I would like to plot the results in different plots because now the prediction bands overlap. I tried to save the output (lpb and upb) in a dataframe (predictionbounds) but I get an error and I think this approach is not elegant. How can I get 4 different plots out of the loop??
## 1,2,3 are functions I use in the loop
# 1) linear model
def model(x, y, start):
return (b*x) + start
# 2) Prediction band
def predband .....
return lpb, upb
# 3) function to calculate CI 0f fitted parameters
def conf_int:........
return params_ci
### prepare dataset for loop
# group dataset in subgroups. Loops is applied in each subgroup
dfforR2 = dfdata.groupby(["treatment1", "treatment2])
variables={'treatment1':treatment1, 'treatment2':'treatment2','b':float, 'start':float,
'r_2':float}
results = pd.DataFrame(variables, index=[])
#Here I try to create an empty dataframe so I can save the variables 'lpb' and 'upb'
#bounds={'treatment1':treatment1, 'treatment2':'treatment2', 'lpb':float, 'upb':float}
#predictionbounds=pd.DataFrame(bounds, index=[])
### loop and make fit
for key, g in dfforR2:
x= np.linspace(0, 2, )
popt, pcov = curve_fit(model, g['x'], g['y'])
confint=(conf_int(g['y'], alpha, popt, pcov))
lpb, upb=predband(x, g['x'], g['y'], popt, model, conf=0.95)
new_row = {'treatment1':key[0], 'treatment2':key[1], 'slope': popt[0], 'start':popt[1],
'r_2':r_2}
results=results.append(new_row, ignore_index=True)
Problem starts below:
#line below does not work as I get an error:
#AttributeError: 'dict' object has no attribute 'append'
#new_bound = {'treatment1':key[0], 'treatment2':key[1], ' lpb': lpb, 'upb':upb}
#this works but I would like to print different graphs
plt.fill_between(x, lpb, upb, color = 'grey', alpha = 0.15)
#### Plot manually the output
# construct fitted curve for this treatment
#x= np.linspace(0, 1500, 400)
a = model(x, results.iloc[0,2], results.iloc[0,3])
plt.plot(x, a, color='tab:blue', label='Ctrl_W')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

