bokeh绘制小提琴图
Posted On 2018-09-11
|
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 |
from scipy.stats.kde import gaussian_kde from bokeh.models import ColumnDataSource, FixedTicker, PrintfTickFormatter from bokeh.plotting import figure from bokeh.sampledata.perceptions import probly def get_summary_stats(x=None, y=None, data=None): # create a df of just the two variables and summarize it dt = data[[x, y]] # make a group by object to be used later. dtg = dt.groupby(x)[y] st = dtg.agg([('q1', lambda z: np.percentile(z, 25)), ('med', lambda z: np.percentile(z, 50)), ('q3', lambda z: np.percentile(z, 75)), ("mean", np.mean)]) st['iqr'] = st['q3'] - st['q1'] st['lwl'] = st['q1'] - 1.5 * st['iqr'] st['uwl'] = st['q3'] + 1.5 * st['iqr'] # join the uwl and lwl to the raw data, check if outlier and store boolean with data table dt = dt.join(st[['lwl', 'uwl']], on=x) dt['outlier'] = ~dt[y].between(dt['lwl'], dt['uwl']) # get the values of the upper and lower whiskers based on the min and max non-outliers (Tukey Boxplot) st = dt[~dt.outlier].groupby(x)[y].agg([('lwp', np.min), ('uwp', np.max)]).join(st) # only return the bare minimum in the summary table and data table. return st.drop(['uwl', 'lwl'], axis=1), dt[[x, y, 'outlier']] def make_violin_plot2(x=None, y=None, data=None, title = None, width=800, height=600, whisker_line_width=1, whisker_line_color = "black", inchi_2_formula_and_compoundid = {}, bw_method='scott', violin_padding=.1, grid_points=50, violin_width=.8, line_color=None, fill_color = "lightskyblue",**kwargs): # make a data frame of just the variables needed, and drop missing values. dt = data[[x, y]].dropna() # create a figure if one does not already exist # if plot is None:, # ("mean", np.mean), # ("mean", np.mean) # plot = make_base_plot(x=x, y=y, data=dt) # TOOLTIPS = [ # ("compound", "@compound") # ] # plot = figure(x_range=list(data[x].cat.categories), width=width, height=height,toolbar_location="above") plot = figure(x_range=list(data[x].cat.categories), width=width, height=height,toolbar_location="above") plot.outline_line_color = 'grey' plot.outline_line_width = 1 # styling - title if title: plot.title = Title(text=title, align="center") #plot.title_text_font_size = "12pt" # styling - grid lines plot.xgrid.grid_line_color = None # styling - axis labels # plot.xaxis.axis_label = x # plot.xaxis.axis_label_text_font_size = "12pt" # plot.yaxis.axis_label = y # plot.yaxis.axis_label_text_font_size = "12pt" # styling - axes lines plot.xaxis.axis_line_color = None plot.yaxis.axis_line_color = None plot.xaxis.major_label_text_align = "center" # styling - axes ticks plot.axis.major_tick_out = 4 plot.axis.major_tick_in = 0 plot.yaxis.minor_tick_line_color = None plot.xaxis.major_label_orientation = 1 # ******************* # *** Add Violins *** # ******************* ix = 0.5 for category in dt[x].cat.categories: # print category # subset values and get kde function. y_data = dt[dt[x] == category][y] # If kde can be calculated, then compute pdf values and add to plot if len(y_data) > 1: # define the points within the range over which to compute the pdf. y_min, y_max = y_data.min(), y_data.max() y_padding = (y_max - y_min) * violin_padding y_grid = np.linspace(y_min - y_padding, y_max + y_padding, grid_points) # get the pdf function for the y_data, compute and normalize the pdf values to desired width pdf = stats.gaussian_kde(y_data, bw_method) x_pdf = pdf(y_grid) x_pdf = x_pdf / x_pdf.max() * violin_width / 2 # Build arrays that describe the patch points by appending reversed arrays (and negated for x) x_patch = np.append(x_pdf, -x_pdf[::-1]) # negated and reversed to get the left side of the violin y_patch = np.append(y_grid, y_grid[::-1]) # reversed to start left violin where right violin ended # add the patch to the plot # plot.patch((x_patch + ix), y_patch, alpha=1, color=fill_color, line_color='grey', line_width=1) source = ColumnDataSource(dict(x = x_patch + ix, y = y_patch, compound = ["compound"]*len(y_patch))) plot.patch("x", "y",source = source, alpha=1, color=fill_color, line_color='grey', line_width=1) ix += 1 # print (x_patch + ix), y_patch # ******************************** # *** Add boxes and raw points *** # ******************************** # summarize the data and mark the outliers in the data table st, dt = get_summary_stats(x, y, dt) st["compound"] = st.index.astype('str') box_width=violin_width/4 # if show_boxes: # plot = make_box_plot(x=x, y=y, data=dt, st=st, # box_width=violin_width/4, plot=plot, show_outliers=False, show_points=False, **kwargs) st['xc'] = st.index.codes + 0.5 # plot.segment(st['xc'] - box_width / 2, st['q3'], st['xc'] + box_width / 2, st['q3'], # line_color=whisker_line_color, line_width=whisker_line_width) # plot.segment(st['xc'] - box_width / 2, st['q1'], st['xc'] + box_width / 2, st['q1'], # line_color=whisker_line_color, line_width=whisker_line_width) # # plot median # plot.segment(st['xc'] - box_width , st['med'], st['xc'] + box_width , st['med'], # line_color="orangered", line_width=whisker_line_width) # # plot.line(st['xc'] , st['mean'], line_color = "red", line_dash = "5 5", line_width = 2) # plot.add_tools(HoverTool(tooltips = [('compound', '@compound')])) # plot.circle(st['xc'] , st['mean'], color = "red", size = 10) # # plot lower and upper whiskers (x0, y0, x1, y1) # plot.segment(st['xc'], st['q1'], st['xc'], st['lwp'], # line_color=whisker_line_color, line_width=whisker_line_width) # # plot.segment(st['xc'], st['q3'], st['xc'], st['uwp'], # # line_color=whisker_line_color, line_width=whisker_line_width) # plot.segment(st['xc'], st['q1'], st['xc'], st['uwp'], # line_color=whisker_line_color, line_width=whisker_line_width) # # plot lower and upper whisker terminations # plot.segment(st['xc'] - box_width / 6, st['uwp'], st['xc']+box_width / 6, st['uwp'], # line_color=whisker_line_color, line_width=whisker_line_width) # plot.segment(st['xc'] - box_width / 6, st['lwp'], st['xc']+box_width / 6, st['lwp'], # line_color=whisker_line_color, line_width=whisker_line_width) ############### ## HoverTool ## ############### plot.segment("x1", "y1","x2", "y2",source = ColumnDataSource(dict(x1=st['xc'] - box_width / 2, y1=st['q3'], x2=st['xc'] + box_width / 2, y2=st['q3'], compound=st["compound"])), line_color=whisker_line_color, line_width=whisker_line_width) plot.segment("x1", "y1","x2", "y2",source = ColumnDataSource(dict(x1=st['xc'] - box_width / 2, y1=st['q1'], x2=st['xc'] + box_width / 2, y2=st['q1'], compound=st["compound"])), line_color=whisker_line_color, line_width=whisker_line_width) # plot median plot.segment("x1", "y1","x2", "y2",source = ColumnDataSource(dict(x1=st['xc'] - box_width , y1=st['med'], x2=st['xc'] + box_width , y2=st['med'], compound=st["compound"])), line_color="orangered", line_width=whisker_line_width) plot.line("x", "y",source = ColumnDataSource(dict(x=st['xc'] ,y= st['mean'], compound=st["compound"])), line_color = "red", line_dash = "5 5", line_width = 2) plot.add_tools(HoverTool(tooltips = [('compound', '@compound')])) plot.circle("x", "y",source = ColumnDataSource(dict(x=st['xc'] , y=st['mean'], compound=st["compound"])), color = "red", size = 10) # plot lower and upper whiskers (x0, y0, x1, y1) plot.segment("x1", "y1","x2", "y2",source = ColumnDataSource(dict(x1=st['xc'], y1=st['q1'], x2=st['xc'], y2=st['lwp'], compound=st["compound"])), line_color=whisker_line_color, line_width=whisker_line_width) # plot.segment(st['xc'], st['q3'], st['xc'], st['uwp'], # line_color=whisker_line_color, line_width=whisker_line_width) plot.segment("x1", "y1","x2", "y2",source = ColumnDataSource(dict(x1=st['xc'], y1=st['q1'], x2=st['xc'], y2=st['uwp'], compound=st["compound"])), line_color=whisker_line_color, line_width=whisker_line_width) # plot lower and upper whisker terminations plot.segment("x1", "y1","x2", "y2",source = ColumnDataSource(dict(x1=st['xc'] - box_width / 6, y1=st['uwp'], x2 = st['xc']+box_width / 6, y2=st['uwp'], compound=st["compound"])), line_color=whisker_line_color, line_width=whisker_line_width) plot.segment("x1", "y1","x2", "y2",source = ColumnDataSource(dict(x1=st['xc'] - box_width / 6, y1=st['lwp'], x2=st['xc']+box_width / 6, y2 = st['lwp'], compound=st["compound"])), line_color=whisker_line_color, line_width=whisker_line_width) return plot |
参考:https://github.com/rsgoodwin/splot