Repository navigation
Expand file tree
/
Copy pathmultiple_lm_plot1.py
More file actions
230 lines (172 loc) · 9.36 KB
/
Copy pathmultiple_lm_plot1.py
File metadata and controls
230 lines (172 loc) · 9.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# monte carlo estimate
import math
import random
import numpy as np
import pandas as pd
from sklearn.metrics import r2_score
import matplotlib.pyplot as plt
#import numpy as np
#import pandas as pd
#from scipy import stats
#import textwrap
#import statsmodels.formula.api as smf
#import statsmodels.api as sm
#from matplotlib import pyplot as plt
#from sklearn.linear_model import LinearRegression
#from sklearn.preprocessing import PolynomialFeatures
#from sklearn.metrics import r2_score
#df <- data.frame(xx=rnorm(200), yy=rnorm(200), zz=rep(c("a","b", "c", "d"),times=50))
#df <- data.frame(xx=seq(1,200,1), yy=rep(c(1,2,3,2),each=50), zz=rep(c("a","b", "c", "d"),times=50))
df = pd.DataFrame({'xx':np.random.normal(0,1,200), 'yy':np.random.normal(0,1,200), 'zz':["a","b","c","d"]*50})
#df = pd.DataFrame({'xx':range(0,200,1), 'yy':[1,2,3,4]*50, 'zz':["a","b","c","d"]*50})
x_name = "xx"
group_var = "zz"
# graph by group
# for every column in df
for column in df.columns:
# select the columns of interest
df_tst = df[[x_name, column, group_var]]
if (x_name is not column) & (df[column].dtype.kind in 'biufc'): # column type is numeric
# get boxplot data
labels = df_tst[group_var].unique()
collection=[]
for label in labels:
test = df_tst[df_tst[group_var]==label]
collection.append(df_tst[column][df_tst[group_var]==label].to_list())
# boxplot
fig, ax = plt.subplots()
#ax.boxplot(x=df_num[i], labels=labels, showmeans = False)
ax.boxplot(collection, tick_labels=labels)
ax.grid(linestyle='',color='#CECECE')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.set_xlabel(str(group_var),size=10)
ax.set_ylabel("Number", size=10)
ax.set_title('Title',size=12)
# annotate graph
#for x in zip()
#set size of graph
cmsize=1/2.54
fig.set_size_inches(30*cmsize, 15*cmsize)
plt.show()
########## plot scatter by group_var
# get equations by type
unq_cat = len(labels) # get count of how many unique group types
fig, ax = plt.subplots(unq_cat, sharex=True)
# for each group, make a separate graph
for axi in range(0,unq_cat,1):
ax[axi].scatter(df_tst[x_name][df_tst[group_var]==labels[axi]], df_tst[column][df_tst[group_var]==labels[axi]])
xxx = df_tst[x_name][df_tst[group_var]==labels[axi]]
yyy = df_tst[column][df_tst[group_var]==labels[axi]]
# make smooth linear and polynominal estimates
# lr
poly_lr = np.polyfit(xxx, yyy, deg=1, rcond=None, full=False, w=None, cov=False)
p_lr = np.poly1d(poly_lr)
p_lr = r2_score(yyy, p_lr(xxx))
xs = np.linspace(min(xxx), max(xxx), 100)
ys = poly_lr[0] * xs + poly_lr[1]
ax[axi].plot(xs, ys, color='blue')#, label=f'$({poly_lr[0]:.2f})x + ({poly_lr[1]:.2f}); r^2={p_lr}$')
# poly
poly_ply = np.polyfit(xxx, yyy, deg=3, rcond=None, full=False, w=None, cov=False)
p_ply= np.poly1d(poly_ply)
p_ply = r2_score(yyy, p_ply(xxx))
xs_ply = np.linspace(min(xxx), max(xxx), 100)
ys_ply = poly_ply[0] * xs ** 3 + poly_ply[1] * xs ** 2 + poly_ply[2] * xs + poly_ply[3]
ax[axi].plot(xs_ply, ys_ply, color='red')#, label=f'$({poly_ply[0]:.2f})x^3+({poly_ply[1]:.2f})x^2+({poly_ply[2]:.2f})x + ({poly_ply[3]:.2f}); r^2={p_ply}$')
# annotate equations
#ax[axi].annotate(min(xxx),min(yyy),)
ax[axi].annotate(f'y=$({poly_lr[0]:.2f})x + ({poly_lr[1]:.2f})$; $r^2={p_lr:.2f}$',
xy=(np.mean(xxx),max(yyy)),
xytext=(15, 0), # 4 points vertical offset.
textcoords='offset points',
ha='center', va='bottom', color="blue")
ax[axi].annotate(f'y=$({poly_ply[0]:.2f})x^3+({poly_ply[1]:.2f})x^2+({poly_ply[2]:.2f})x + ({poly_ply[3]:.2f})$; $r^2={p_ply:.2f}$',
xy=(np.mean(xxx),min(yyy)),
xytext=(0, 0), # 4 points vertical offset.
textcoords='offset points',
ha='center', va='bottom', color="red")
#ax.boxplot(x=df_num[i], labels=labels, showmeans = False)
#ax.boxplot(collection, tick_labels=labels)
ax[axi].grid(linestyle='',color='#CECECE')
ax[axi].spines['top'].set_visible(False)
ax[axi].spines['right'].set_visible(False)
#ax[axi].set_xlabel(str(group_var),size=10)
#ax[axi].set_ylabel("Number", size=10)
#ax[axi].set_title('Title',size=12)
ax[axi].set_title(f"\n{str(labels[axi])}",size=10, loc="right")
# only show xlabs for bottom graph
if axi != unq_cat-1:
ax[axi].get_xaxis().set_visible(False)
ax[axi].set_xlabel=""
ax[axi].xlabs=""
# annotate graph
#for x in zip()
ax[0].set_title("Title",size=10)
#set size of graph
cmsize=1/2.54
fig.set_size_inches(30*cmsize, 15*cmsize)
plt.show()
########## plot scatter by group_var as multiple rows and columns of graphs
# get equations by type
unq_cat = len(labels) # get count of how many unique group types this is number of columns
num_rows = math.ceil(unq_cat / 2)
fig, ax = plt.subplots(num_rows, 2, sharex = True)
ax = ax.flatten()
# for each group, make a separate graph
for axi in range(0,unq_cat,1):
ax[axi].scatter(df_tst[x_name][df_tst[group_var]==labels[axi]], df_tst[column][df_tst[group_var]==labels[axi]])
xxx = df_tst[x_name][df_tst[group_var]==labels[axi]]
yyy = df_tst[column][df_tst[group_var]==labels[axi]]
# make smooth linear and polynominal estimates
# lr
poly_lr = np.polyfit(xxx, yyy, deg=1, rcond=None, full=False, w=None, cov=False)
p_lr = np.poly1d(poly_lr)
p_lr = r2_score(yyy, p_lr(xxx))
xs = np.linspace(min(xxx), max(xxx), 100)
ys = poly_lr[0] * xs + poly_lr[1]
ax[axi].plot(xs, ys, color='blue')#, label=f'$({poly_lr[0]:.2f})x + ({poly_lr[1]:.2f}); r^2={p_lr}$')
# poly
poly_ply = np.polyfit(xxx, yyy, deg=3, rcond=None, full=False, w=None, cov=False)
p_ply= np.poly1d(poly_ply)
p_ply = r2_score(yyy, p_ply(xxx))
xs_ply = np.linspace(min(xxx), max(xxx), 100)
ys_ply = poly_ply[0] * xs ** 3 + poly_ply[1] * xs ** 2 + poly_ply[2] * xs + poly_ply[3]
ax[axi].plot(xs_ply, ys_ply, color='red')#, label=f'$({poly_ply[0]:.2f})x^3+({poly_ply[1]:.2f})x^2+({poly_ply[2]:.2f})x + ({poly_ply[3]:.2f}); r^2={p_ply}$')
# annotate equations
#ax[axi].annotate(min(xxx),min(yyy),)
ax[axi].annotate(f'y=$({poly_lr[0]:.2f})x + ({poly_lr[1]:.2f})$; $r^2={p_lr:.2f}$',
xy=(np.mean(xxx),max(yyy)),
xytext=(15, 0), # 4 points vertical offset.
textcoords='offset points',
ha='center', va='bottom', color="blue")
ax[axi].annotate(f'y=$({poly_ply[0]:.2f})x^3+({poly_ply[1]:.2f})x^2+({poly_ply[2]:.2f})x + ({poly_ply[3]:.2f})$; $r^2={p_ply:.2f}$',
xy=(np.mean(xxx),min(yyy)),
xytext=(0, 0), # 4 points vertical offset.
textcoords='offset points',
ha='center', va='bottom', color="red")
#ax.boxplot(x=df_num[i], labels=labels, showmeans = False)
#ax.boxplot(collection, tick_labels=labels)
ax[axi].grid(linestyle='',color='#CECECE')
ax[axi].spines['top'].set_visible(False)
ax[axi].spines['right'].set_visible(False)
#ax[axi].set_xlabel(str(group_var),size=10)
#ax[axi].set_ylabel("Number", size=10)
#ax[axi].set_title('Title',size=12)
ax[axi].set_title(f"\n{str(labels[axi])}",size=10, loc="center")
# only show xlabs for bottom graphs
# series for nums
xx = [i for i in range(unq_cat-2, unq_cat,1)]
if axi not in xx:
ax[axi].get_xaxis().set_visible(False)
ax[axi].set_xlabel=""
ax[axi].xlabs=""
# Hide unused subplots
for j in range(unq_cat + 1, len(ax)):
ax[j].axis('off')
# annotate graph
#for x in zip()
#ax[0].set_title("Title",size=10)
#set size of graph
cmsize=1/2.54
fig.set_size_inches(30*cmsize, 15*cmsize)
plt.show()