-
Notifications
You must be signed in to change notification settings - Fork 0
/
interactive_plot2.py
219 lines (163 loc) · 7.23 KB
/
interactive_plot2.py
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
import bokeh.io
from bokeh.io import output_notebook, show
from bokeh.layouts import row,column
from bokeh.models import CustomJS, ColumnDataSource,Button,LogColorMapper,LinearColorMapper
from bokeh.plotting import figure
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn
from bokeh.palettes import Spectral6
from bokeh.transform import factor_cmap
from bokeh.resources import INLINE
bokeh.io.output_notebook(INLINE)
import pandas as pd
def select_points_scatter(data,X = 'X', Y = 'Y', hue = 'hue',factor_type = 'categorical',group = 'group',alpha = .6,plot_width = 400,plot_height = 400,palette = Spectral6,vmin = 0, vmax = 3
):
'''source: dataframe with required columns for x and y positions as well as group name and color for each group.'''
#initialize coloring
if factor_type == 'categorical':
color = factor_cmap(hue,palette = palette,factors = list(data[hue].unique()))
elif factor_type == 'continuous':
color_mapper = LinearColorMapper(palette = palette,low = vmin,high = vmax)
color = {'field':hue,'transform':color_mapper}
else:
raise ValueError('factor_type must be \'continuous\' or \'categorical\'')
#initialize main plot
s1 = ColumnDataSource(data=data)
p1 = figure(plot_width=400, plot_height=400, tools="pan,wheel_zoom,lasso_select,reset", title="Select Here")
p1.circle(X, Y, source=s1, alpha = alpha,color = color)
#### initialize selected plot
s2 = ColumnDataSource(data={X:[],Y:[],group:[],hue:[]})
p2 = figure(plot_width=400, plot_height=400,
tools="", title="Watch Here",
x_range = p1.x_range,y_range = p1.y_range)
p2.circle(X,Y, source=s2, alpha=alpha,color = color)
#initialize table to show selected points
columns = [TableColumn(field =X, title = "X axis"),
TableColumn(field =Y, title = "Y axis"),
TableColumn(field =group, title = group)]
table = DataTable(source =s2, columns = columns, width =155, height = plot_height-20)
#define callback when points are selected
s1.selected.js_on_change('indices', CustomJS(args=dict(s1=s1, s2=s2, table=table,
X = X, Y = Y,hue = hue,group = group,
), code="""
var inds = cb_obj.indices;
var d1 = s1.data;
var d2 = s2.data;
d2[X] = []
d2[Y] = []
d2[hue] = []
d2[group] = []
for (var i = 0; i < inds.length; i++) {
d2[X].push(d1[X][inds[i]])
d2[Y].push(d1[Y][inds[i]])
d2[hue].push(d1[hue][inds[i]])
d2[group].push(d1[group][inds[i]])
}
s2.change.emit();
table.change.emit();
""")
)
savebutton = Button(label="Save", button_type="success",width =155)
javaScript="""
function table_to_csv(source) {
const columns = Object.keys(source.data)
const nrows = source.get_length()
const lines = [columns.join(',')]
for (let i = 0; i < nrows; i++) {
let row = [];
for (let j = 0; j < columns.length; j++) {
const column = columns[j]
row.push(source.data[column][i].toString())
}
lines.push(row.join(','))
}
return lines.join('\\n').concat('\\n')
}
const filename = 'data_result.csv'
filetext = table_to_csv(source)
const blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' })
//addresses IE
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, filename)
} else {
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = filename
link.target = '_blank'
link.style.visibility = 'hidden'
link.dispatchEvent(new MouseEvent('click'))
}
"""
savebutton.callback = CustomJS(
args=dict(source=s2,index_col = group),
code=javaScript)
layout = row(p1, p2, column(table,savebutton))
show(layout)
def show_cells_on_stack(data,stack,X='X',Y='Y',channelNames = None,
group = 'group',hue = 'hue',palette = 'Spectral11',
default = 0, alpha = .5,
plot_width = 500,plot_height = 500,
vmin = 0,vmax = 3,znorm = True):
'''
stack: np. array of shape (nchannels,height,width)
'''
from bokeh.models import CheckboxGroup,RadioButtonGroup,Legend, LegendItem
if not channelNames:
channelNames = ['Channel '+str(i) for i in range(len(stack))]
print (channelNames)
s1 = ColumnDataSource(data=data)
p1 = figure(plot_width=plot_width, plot_height=plot_height, tools="pan,wheel_zoom,reset")
channels = {}
for i,channel in enumerate(channelNames):
img = stack[i]
if znorm:
img = (img-img.mean())/img.std()
channels[i] = p1.image(image = [img],x = [0],y = [0],dw = [plot_width],dh = [plot_height],
color_mapper = LogColorMapper(palette = palette,low = vmin,high = vmax),
global_alpha = alpha,visible =(i==default))
plots = {}
#scaled_coordinates to fit in stack_dw,stack_dh
dh_ratio = plot_height/img.shape[0]
dw_ratio = plot_width/img.shape[1]
data['warped_X'] = data[X]*dw_ratio
data['warped_Y'] = data[Y]*dh_ratio
groups = list(data[group].unique())
for g_id in groups:
s2 = ColumnDataSource(data = data[data[group]==g_id])
scatter = p1.circle('warped_X','warped_Y', source=s2, alpha = 1,color = 'hue')#,legend_label = str(g_id))
scatter.visible = False
plots[g_id] = scatter
select_celltype = CheckboxGroup(labels = groups,active = [],
width = 100)
select_channel = RadioButtonGroup(labels = channelNames,active = default,
width = 100,orientation = 'horizontal')
select_celltype.callback = CustomJS(args = {'plots':plots,'groups':groups,
'msel':select_celltype,'fig':p1},code = """
//fig.title.text = 'new Title'
for (var i =0; i<groups.length;i++){
plots[groups[i]].visible = msel.active.indexOf(i)>-1
}
""")
select_channel.callback = CustomJS(args = {'channels':channels,'sel':select_channel,
'fig':p1},code = """
//fig.title.text = Object.keys(channels).length.toString()
for (var i =0; i<Object.keys(channels).length;i++){
channels[i].visible = false
}
var val = sel.active
channels[val].visible = true
/**
if (val==0){
fig.title.text = 'confirm upper'
chan1.visible = true
chan2.visible = false
//bg_channel = [z[0]]
}else if (val==1){
fig.title.text = 'confirm lower'
chan1.visible = false
chan2.visible = true
//bg_channel = [z[1]]
}
**/
""")
layout = column(p1,select_celltype,select_channel)
show(layout)