def sb_violinplot(series, dataframe=None, groupCol=None, **kwargs): import pandas as pd import seaborn as sns if not groupCol: assert isinstance(series, pd.Series) return to_bokeh(sns.violinplot(x=series, **kwargs).figure) else: assert dataframe and groupCol assert isinstance(series, str) return to_bokeh( sns.violinplot(x=groupCol, y=series, data=dataframe, **kwargs).figure)
def mc_results(self): # Compute Monte Carlo results Y = self.Y.as_matrix() Y0 = float(self.ticker4_1) hist_point = int(self.ticker4) num_paths = int(self.ticker3) center_point = np.mean(Y[hist_point,:]) stkgrid = np.linspace(0.5*center_point,1.5*center_point,100) meanlst = np.array([]) stdlst = np.array([]) paylst = np.array([]) for stk in stkgrid: meanlst = np.append(meanlst, np.mean(payoff(Y[hist_point,:],stk))) stdlst = np.append(stdlst,np.std(payoff(Y[hist_point,:],stk))/np.sqrt(num_paths)) plt.plot(stkgrid,meanlst+2*stdlst, 'g-') plt.plot(stkgrid,meanlst-2*stdlst,'g-',label='2-Sig Error') plt.plot(stkgrid,meanlst+stdlst,'r-') plt.plot(stkgrid,meanlst-stdlst,'r-',label='1-Sig Error') plt.plot(stkgrid,meanlst,'b',label='Mean') plt.title('MC Option Price (Blue) with 1-Sig (Red) and 2-Sig (Green) Errors') plt.xlabel('Strike') plt.ylabel('Value') p = mpl.to_bokeh() p.title_text_font_size= str(TITLE_SIZE)+'pt' return p
def initialize_plot(self, ranges=None, plot=None, plots=None): element = self.hmap.last key = self.keys[-1] self.mplplot.initialize_plot(ranges) plot = mpl.to_bokeh(self.mplplot.state) self.handles['plot'] = plot return plot
def test(datasets="", genes=None, samples=None, chart_type=None, scale=None): data = get_demo_normalized_set() sns.set_style("whitegrid") if chart_type is None or chart_type == "box": data.transpose().boxplot(column=[1, 2, 3], return_type="axes") elif chart_type == "scatter": pass return to_bokeh(name="descriptive")
def acid_violin(acid): olives = pd.read_sql('olives', db.engine, columns=['region', 'area_main', acid]) sns.set_style("whitegrid") sns.mpl.rc("figure", figsize=(15, 6)) ax = sns.violinplot(data=olives, x="area_main", y=acid, cut=0.1, scale='count', title=acid + " acid distribution") bh = mpl.to_bokeh(ax.figure) return bh
def makeplot(dataframe): plt.figure(figsize=(11,8)) dataframe.plot()#df plot function # ax.legend(bbox_to_anchor=(1,1),bbox_transform=plt.gcf().transFigure) plt.legend(fontsize=20,bbox_to_anchor=(1.05,1),loc=2) plt.ylabel('Closing Price',fontsize=15) plt.xlabel('Day',fontsize=15) # fig.savefig('AAPL.png') # output_file("templates/plot.html",title="test") output_file("templates/plot.html",title="closingPrices") # show(mpl.to_bokeh()) save(mpl.to_bokeh())
def update_frame(self, key, ranges=None, plot=None, element=None, empty=False): self.mplplot.update_frame(key, ranges) reused = isinstance(self.hmap, DynamicMap) and self.overlaid if not reused and element is None: element = self._get_frame(key) else: self.current_key = key self.current_frame = element plot = mpl.to_bokeh(self.mplplot.state) update_plot(self.handles['plot'], plot) if not self.overlaid: self._update_plot(key, self.handles['plot'], element)
def initialize_plot(self, ranges=None, plot=None, plots=None): self.mplplot.initialize_plot(ranges) plot = plot if plot else self.handles.get('plot') new_plot = mpl.to_bokeh(self.mplplot.state) if plot: update_plot(plot, new_plot) else: plot = new_plot self.handles['plot'] = plot if not self.overlaid: self._update_plot(self.keys[-1], plot, self.hmap.last) return plot
def plot_pulses2(self, km=False): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from bokeh.resources import CDN from bokeh.embed import components from bokeh.mpl import to_bokeh from bokeh.models.tools import WheelZoomTool, ResetTool, PanTool, HoverTool, SaveTool lines = self.get_lines() N = len(lines) npoints = self.total_units / self.km2unit if km else self.total_units fig = plt.figure(figsize=(12, 2 + N * 0.5)) ax = fig.add_subplot(111) labels = ['IPP'] for i, line in enumerate(lines): labels.append(line.get_name(channel=True)) l = ax.plot((0, npoints), (N - i - 1, N - i - 1)) points = [(tup[0], tup[1] - tup[0]) for tup in line.pulses_as_points(km=km) if tup != (0, 0)] ax.broken_barh(points, (N - i - 1, 0.5), edgecolor=l[0].get_color(), facecolor='none') n = 0 f = ((self.ntx + 50) / 100) * 5 if ( (self.ntx + 50) / 100) * 10 > 0 else 2 for x in np.arange(0, npoints, self.ipp if km else self.ipp * self.km2unit): if n % f == 0: ax.text(x, N, '%s' % n, size=10) n += 1 labels.reverse() ax.set_yticks(range(len(labels))) ax.set_yticklabels(labels) ax.set_xlabel = 'Units' plot = to_bokeh(fig, use_pandas=False) plot.tools = [ PanTool(dimensions=['width']), WheelZoomTool(dimensions=['width']), ResetTool(), SaveTool() ] plot.toolbar_location = "above" return components(plot, CDN)
def plot_comparison(dataset_identifiers, features, type="boxplot"): sns.set_style("whitegrid") sns.set_palette("deep") generator = "matplot" f, axes = plt.subplots(1, 2) # dataset_identifiers = ['DESeq_1_18_0_umc_read_counts_table_without_8433', # 'DESeq_1_18_0_genentech_read_counts_table'] # features = ["ENSG00000002549"] path = APP_CONFIG["application_files_location"] + APP_CONFIG["application_store_name"] i = 0 subset = None print features for d in dataset_identifiers: dataset = dr.get_data_frame_from_hdf(d, path) if type != "pca": subset = dataset.ix[features, :] if type == "boxplot": axes[i].boxplot(subset) create_csv_version(subset.transpose(), d, type, subset.columns) if type == "scatter": generator = "matplot" #print len(subset.ix[0, :]) t = axes[i].plot(subset.transpose(), 'o') create_csv_version(subset.transpose(), d, type, subset.columns) plugins.connect(f, plugins.PointLabelTooltip(t[0], labels=(list(subset.columns)))) if type == "pca": print(type) pca = PCA(n_components=2) t_data = dataset.transpose() pca_result = pca.fit(t_data) pca_transformed = pca_result.transform(t_data) t = axes[i].plot(pca_transformed[:, 0], pca_transformed[:, 1], 'o') create_csv_version(pca_transformed, d, type, dataset.columns) plugins.connect(f, plugins.PointLabelTooltip(t[0], labels=(list(dataset.columns)))) axes[i].set_xlabel(d) axes[i].set_ylabel(str(features)) i += 1 if generator == "bokeh": bk = to_bokeh(name="descriptive") else: bk = plt.gcf() sz = bk.get_size_inches() bk.set_size_inches((sz[0]*2.5, sz[1]*2)) return bk
def plot_multiple_agents(results_path, results_name, num_workers): def _get_data_from_files(): dfs = [] for i_work in range(num_workers): dfs.append( pd.read_json(os.path.abspath(files_name.format(i_work)), lines=True)) df = pd.DataFrame() df['epoch'] = dfs[0]['epoch'] columns = list(dfs[0].columns.values) columns.remove('epoch') columns.remove('time') columns.remove('step') # ensure all matrices of the same size, # since not all agents necessarily reached the same epoch max_epochs = 0 for d in dfs: epochs = d.shape[0] max_epochs = max(max_epochs, epochs) data = {} for c in columns: data[c] = np.vstack([df[c].as_matrix() for df in dfs]) return data, columns files_name = os.path.join(results_path, results_name) plot_path = '{}.{}'.format(files_name, 'html') files_name += '_{}.json' data, columns = _get_data_from_files() figs = [] for i, col in enumerate(columns): fig = plt.figure(i) axis = sns.tsplot(data=data[col], err_style="unit_traces") # axis = sns.tsplot(data=data[c], ci=[50, 70, 90], legend=True) axis.set_title(col) axis.set_xlabel('epochs') axis.set_ylabel(col) fig.add_axes(axis) figs.append(to_bokeh(fig)) plot = column(Div(text='<h1 align="center">{}</h1>'.format(results_name)), *figs) output_file(plot_path, title=results_name) save(plot)
def hist_den_plot(self): Y = self.Y.as_matrix() hist_point = int(self.ticker4) delta_t = float(self.ticker3_2) data = Y[hist_point,:] sns.distplot(data, color='k', hist_kws={"color":"b"}, norm_hist=True) #sns.distplot(data, color='k', hist_kws={"color":"b"}) plt.hist(data) plt.title('Distribution at T = ' + str(np.round(delta_t*hist_point,4)) + ' with Mean: ' +str(np.round(np.mean(data),4)) + ' and Std Dev: ' + str(np.round(np.std(data),4))) plt.xlabel('Price Bins') plt.ylabel('Bin Count') p = mpl.to_bokeh() p.title_text_font_size= str(TITLE_SIZE)+'pt' return p
def bokeh_frisbee(i): """ Creates a bokeh html file of the 3D plot """ from bokeh import mpl from bokeh.plotting import output_file, save fig = plt.figure() fig.canvas.set_window_title('Frisbee Simulation HTML') ax = fig.gca(projection='3d') ax.plot(mat_z[0:i], mat_x[0:i], mat_y[0:i], label='Frisbee Flight') plt.ylabel("X distance (m)") plt.xlabel("Z distance (m)") if absmax(mat_z) < 1: ax.set_xlim(-1, 1) output_file("online_fig.html") save(mpl.to_bokeh(fig)) return
def figtoHTML(figure, pathName): ''' For a given figure object (matplotlib), saves it a specified file path as an HTML file (bokeh format). Args: figure: A matplotlib figure object to save. pathName: Path of file to save figure to. Returns: 1 if successful, 0 if not successful. ''' try: output_file(pathName) bfig = to_bokeh(figure) except: print('Failed to save figure to {}'.format(pathName)) return 0 return 1
def updateFigure(): filename = str(selectFile.value) allData = [] data = [] with open(filePath, 'r') as csvfile: next(csvfile) allData = csv.reader(csvfile, delimiter=',') ##Making word cloud for the selected file data = [row for row in allData if row[1] == filename] print(data) words = [] for row in data: words.append(row[2]) print(words[0]) csvfile.close() wordcloud = WordCloud(background_color="white", max_font_size=40).generate(words[0]) plt.imshow(wordcloud) #, interpolation="bilinear" plt.axis("off") plt.show() fig = mpl.to_bokeh(plt.figure()) return fig
def visualize_data(): data_file = parse(MY_FILE, "~") counter = Counter(item["Product"] for item in data_file) data_list = [ counter["P-HYP"], counter["RTVAST"], counter["A-MKHYP"], counter["P-HYPL"], ] labels_tuple = tuple(["P-HYP", "RTVAST", "A-MKHYP", "P-HYPL"]) plt.title("Test") plt.plot(data_list) plt.xticks(range(len(labels_tuple)), labels_tuple) #Save to bokeh plot = mpl.to_bokeh(name='test') bpl.show(plot) output_file("test1.html") plt.clf()
def path_plot(self): num_paths_plot = min(50,int(self.ticker3)) hist_point = int(self.ticker4) #print 'Hist Point ', hist_point Y = self.Y.as_matrix() pltdat = Y[:,0:num_paths_plot] mY, MY = min(Y[hist_point,:]), max(Y[hist_point,:]) plt.plot(pltdat, alpha=0.1, linewidth=1.8) sns.tsplot(pltdat.T,err_style='ci_band', ci=[68,95,99], alpha=1, \ linewidth = 2.5, color='indianred') #sns.tsplot(pltdat.T,err_style='ci_band', ci=[68,95,99,99.99999], alpha=1, \ # linewidth = 2.5, condition='Mean Path', color='indianred') plt.plot([hist_point, hist_point], [0.99*mY, 1.01*MY], 'k-',label='Time Series Histogram') plt.xlabel('Time Step') plt.ylabel('Price') #plt.legend() p = mpl.to_bokeh() p.title = 'Mean Path (Red), MC Paths (Background) and Density Line (Black)' p.title_text_font_size= str(TITLE_SIZE)+'pt' return p
def plot_left_right(df, colors, plot_column='right', grouping_column='party', folder=RESULT_FOLDER, plot_suffix=""): # median-centered per domain right position df[plot_column] = df[plot_column] - df[plot_column].median() ax = sns.violinplot(x=plot_column, y=grouping_column, data=df[[plot_column, grouping_column]], palette=sns.color_palette(colors), split=True, scale="count", inner="stick", saturation=0.5) ax.set_xlim([0, 1]) ax.set_xticks(np.arange(0, 1, .1)) ax.set_xlabel("links-rechts Index") ax.set_ylabel("Partei") ax.set_facecolor("white") ax.set_title(plot_suffix) output_file(os.path.join(folder, "violinPlot-%s.html" % plot_suffix)) show(mpl.to_bokeh())
import numpy as np import pandas as pd from bokeh import mpl from bokeh.plotting import show ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() p = ts.plot() show(mpl.to_bokeh(name="series"))
import numpy as np import pandas as pd from bokeh import mpl ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD')) df = df.cumsum() df.plot(legend=False) mpl.to_bokeh(name="dataframe")
# a "waterfall" plot or a "stagger" plot. nverts = 60 ncurves = 20 offs = (0.1, 0.0) rs = np.random.RandomState([12345678]) yy = np.linspace(0, 2 * np.pi, nverts) ym = np.amax(yy) xx = (0.2 + (ym - yy) / ym)**2 * np.cos(yy - 0.4) * 0.5 segs = [] for i in range(ncurves): xxx = xx + 0.02 * rs.randn(nverts) curve = list(zip(xxx, yy * 100)) segs.append(curve) colors = [(1.0, 0.0, 0.0, 1.0), (0.0, 0.5, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0), (0.0, 0.75, 0.75, 1.0), (0.75, 0.75, 0, 1.0), (0.75, 0, 0.75, 1.0), (0.0, 0.0, 0.0, 1.0)] col = LineCollection(segs, linewidth=5, offsets=offs) ax = plt.axes() ax.add_collection(col, autolim=True) col.set_color(colors) ax.set_title('Successive data offsets') fig = plt.gcf() show(mpl.to_bokeh(name="lc_offsets"))
import numpy as np import matplotlib.pyplot as plt from bokeh import mpl from bokeh.plotting import show x = np.linspace(-2 * np.pi, 2 * np.pi, 100) y = np.sin(x) z = np.cos(x) plt.plot(x, y, "r-", marker='o') plt.title("Matplotlib Figure in Bokeh") # dashed lines work plt.plot(x, z, "g-x", linestyle="-.") #show(mpl.to_bokeh()) #show(mpl.to_bokeh(name="test")) show(mpl.to_bokeh(plt.gcf(), name="test")) #show(mpl.to_bokeh(plt.gcf(), server="default")) #show(mpl.to_bokeh(plt.gcf(), name="test", server="default"))
verts = np.swapaxes(verts, 0, 1) # In your case, "verts" might be something like: # verts = zip(zip(lon1, lat1), zip(lon2, lat2), ...) # If "data" in your case is a numpy array, there are cleaner ways to reorder # things to suit. facecolors = ['red', 'green', 'blue', 'cyan', 'yellow', 'magenta', 'black'] edgecolors = ['cyan', 'yellow', 'magenta', 'black', 'red', 'green', 'blue'] widths = [5, 10, 20, 10, 5] # Make the collection and add it to the plot. col = PolyCollection(verts, facecolor=facecolors, edgecolor=edgecolors, linewidth=widths, linestyle='--', alpha=0.5) ax = plt.axes() ax.add_collection(col) plt.xlim([-60, 60]) plt.ylim([-60, 60]) plt.title("MPL-PolyCollection support in Bokeh") output_file("polycollection.html", title="polycollection.py example") show(mpl.to_bokeh())
plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.ylabel('I', fontsize=20) plt.subplot(222) plt.plot(x, y2, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), yticklabels=[], xticks=(0, 10, 20)) plt.ylabel('II', fontsize=20) plt.subplot(223) plt.plot(x, y3, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.ylabel('III', fontsize=20) plt.setp(plt.gca(), yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.subplot(224) xfit = np.array([np.amin(x4), np.amax(x4)]) plt.plot(x4, y4, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), yticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.ylabel('IV', fontsize=20) # We create the figure in matplotlib and then we "pass it" to Bokeh mpl.to_bokeh(name="subplots")
import numpy as np import matplotlib.pyplot as plt from bokeh import mpl from bokeh.plotting import show x = np.linspace(-2 * np.pi, 2 * np.pi, 100) y = np.sin(x) z = np.cos(x) plt.plot(x, y, "r-", marker='o') plt.title("Matplotlib Figure in Bokeh") # dashed lines work plt.plot(x, z, "g-x", linestyle="-.") #show(mpl.to_bokeh()) #show(mpl.to_bokeh(name="sincos")) show(mpl.to_bokeh(plt.gcf(), name="sincos")) #show(mpl.to_bokeh(plt.gcf(), server="default")) #show(mpl.to_bokeh(plt.gcf(), name="sincos", server="default"))
from ggplot import * from bokeh import mpl import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({ "x": range(100), "y": np.random.choice([-1, 1], 100) }) df.y = df.y.cumsum() g = ggplot(aes(x='x', y='y'), data=df) + \ geom_step() g.draw() plt.title("Step ggplot-based plot in Bokeh.") mpl.to_bokeh(name="step")
ax.plot(sel_by_wave1[j].wave.iloc[i], sel_by_wave1[j].abs_cal.iloc[i], marker='', color=colors[i], lw=0.1) for i in range(len(sel_by_wave1[j].wave)) ] for j in range(len(sel_by_wave1))] ax.set_xlabel(u'Wavelength [\AA]') ax.set_ylabel(u'abs\_cal [erg s$^{-1}$ cm$^{-2}$ \AA$^{-1}$]') # USING BOKEH TOOLS = 'pan, box_zoom, wheel_zoom, hover, resize, undo, redo, reset, save' # x = sel_by_wave1[0].wave.iloc[0] # y = sel_by_wave1[0].abs_cal.iloc[0] # # output_file('delOri.html') # p = figure(tools=TOOLS) # # [p.line(x, y, color=color) for x, y, color in zip(sel_by_wave1[0].wave, sel_by_wave1[0].abs_cal, ['red', 'green'])] # # session = push_session(curdoc()) # # session.show(p) # session.loop_until_closed() output_file('delOri.html') show(to_bokeh(fig, tools=TOOLS)) fig.savefig('./RESULTS/spec_l1240.pdf') plt.clf() plt.close('all')
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from scipy import optimize from bokeh import mpl # Set the palette colors. sns.set(palette="Set2") # Build the sin wave def sine_wave(n_x, obs_err_sd=1.5, tp_err_sd=.3): x = np.linspace(0, (n_x - 1) / 2, n_x) y = np.sin(x) + np.random.normal(0, obs_err_sd) + np.random.normal(0, tp_err_sd, n_x) return y sines = np.array([sine_wave(31) for _ in range(20)]) # Generate the Seaborn plot with "ci" bars. ax = sns.tsplot(sines, err_style="ci_bars", interpolate=False) xmin, xmax = ax.get_xlim() x = np.linspace(xmin, xmax, sines.shape[1]) out, _ = optimize.leastsq(lambda p: sines.mean(0) - (np.sin(x / p[1]) + p[0]), (0, 2)) a, b = out xx = np.linspace(xmin, xmax, 100) plt.plot(xx, np.sin(xx / b) + a, c="#444444") plt.title("Seaborn tsplot with CI in bokeh.") mpl.to_bokeh(name="sinerror")
def plot_2d_graph(self, data_frame, gp, chart_type): if gp is None: gp = GraphProperties() if gp.chart_type is None and chart_type is None: chart_type = 'line' if gp.resample is not None: data_frame = data_frame.asfreq(gp.resample) self.apply_style_sheet(gp) # create figure & add a subplot fig = plt.figure(figsize = ((gp.width * gp.scale_factor)/gp.dpi, (gp.height * gp.scale_factor)/gp.dpi), dpi = gp.dpi) ax = fig.add_subplot(111) if gp.x_title != '': ax.set_xlabel(gp.x_title) if gp.y_title != '': ax.set_ylabel(gp.y_title) plt.xlabel(gp.x_title) plt.ylabel(gp.y_title) fig.suptitle(gp.title, fontsize = 14 * gp.scale_factor) # format Y axis y_formatter = matplotlib.ticker.ScalarFormatter(useOffset = False) ax.yaxis.set_major_formatter(y_formatter) # create a second y axis if necessary ax2 = [] if gp.y_axis_2_series != []: ax2 = ax.twinx() # do not use a grid with multiple y axes ax.yaxis.grid(False) ax2.yaxis.grid(False) # matplotlib 1.5 try: cyc = matplotlib.rcParams['axes.prop_cycle'] color_cycle = [x['color'] for x in cyc] except KeyError: # pre 1.5 pass # color_cycle = matplotlib.rcParams['axes.color_cycle'] bar_ind = np.arange(0, len(data_frame.index)) # for bar charts, create a proxy x-axis (then relabel) xd, bar_ind, has_bar, no_of_bars = self.get_bar_indices(data_frame, gp, chart_type, bar_ind) # plot the lines (using custom palettes as appropriate) try: # get all the correct colors (and construct gradients if necessary eg. from 'blues') color_spec = self.create_color_list(gp, data_frame) # for stacked bar yoff_pos = np.zeros(len(data_frame.index.values)) # the bottom values for stacked bar chart yoff_neg = np.zeros(len(data_frame.index.values)) # the bottom values for stacked bar chart zeros = np.zeros(len(data_frame.index.values)) # for bar chart bar_space = 0.2 bar_width = (1 - bar_space) / (no_of_bars) bar_index = 0 has_matrix = False # some lines we should exclude from the color and use the default palette for i in range(0, len(data_frame.columns.values)): if gp.chart_type is not None: if isinstance(gp.chart_type, list): chart_type = gp.chart_type[i] else: chart_type = gp.chart_type if chart_type == 'heatmap': # TODO experimental! # ax.set_frame_on(False) ax.pcolor(data_frame, cmap=plt.cm.Blues, alpha=0.8) # plt.colorbar() has_matrix = True break label = str(data_frame.columns[i]) ax_temp = self.get_axis(ax, ax2, label, gp.y_axis_2_series) yd = data_frame.ix[:,i] if color_spec[i] is None: color_spec[i] = color_cycle[i % len(color_cycle)] if (chart_type == 'line'): linewidth_t = self.get_linewidth(label, gp.linewidth, gp.linewidth_2, gp.linewidth_2_series) if linewidth_t is None: linewidth_t = matplotlib.rcParams['axes.linewidth'] ax_temp.plot(xd, yd, label = label, color = color_spec[i], linewidth = linewidth_t) elif(chart_type == 'bar'): # for multiple bars we need to allocate space properly bar_pos = [k - (1 - bar_space) / 2. + bar_index * bar_width for k in range(0,len(bar_ind))] ax_temp.bar(bar_pos, yd, bar_width, label = label, color = color_spec[i]) bar_index = bar_index + 1 elif(chart_type == 'stacked'): bar_pos = [k - (1 - bar_space) / 2. + bar_index * bar_width for k in range(0,len(bar_ind))] yoff = np.where(yd > 0, yoff_pos, yoff_neg) ax_temp.bar(bar_pos, yd, label = label, color = color_spec[i], bottom = yoff) yoff_pos = yoff_pos + np.maximum(yd, zeros) yoff_neg = yoff_neg + np.minimum(yd, zeros) # bar_index = bar_index + 1 elif(chart_type == 'scatter'): ax_temp.scatter(xd, yd, label = label, color = color_spec[i]) if gp.line_of_best_fit is True: self.trendline(ax_temp, xd.values, yd.values, order=1, color= color_spec[i], alpha=1, scale_factor = gp.scale_factor) # format X axis self.format_x_axis(ax, data_frame, gp, has_bar, bar_ind, has_matrix) except: pass if gp.display_source_label == True: ax.annotate('Source: ' + gp.source, xy = (1, 0), xycoords='axes fraction', fontsize=7 * gp.scale_factor, xytext=(-5 * gp.scale_factor, 10 * gp.scale_factor), textcoords='offset points', ha='right', va='top', color = gp.source_color) if gp.display_brand_label == True: self.create_brand_label(ax, anno = gp.brand_label, scale_factor = gp.scale_factor) leg = [] leg2 = [] loc = 'best' # if we have two y-axis then make sure legends are in opposite corners if ax2 != []: loc = 2 try: leg = ax.legend(loc = loc, prop={'size':10 * gp.scale_factor}) leg.get_frame().set_linewidth(0.0) leg.get_frame().set_alpha(0) if ax2 != []: leg2 = ax2.legend(loc = 1, prop={'size':10 * gp.scale_factor}) leg2.get_frame().set_linewidth(0.0) leg2.get_frame().set_alpha(0) except: pass try: if gp.display_legend is False: if leg != []: leg.remove() if leg2 != []: leg.remove() except: pass try: plt.savefig(gp.file_output, transparent=False) except: pass ####### various matplotlib converters are unstable # convert to D3 format with mpld3 try: # output matplotlib charts externally to D3 based libraries import mpld3 if gp.display_mpld3 == True: mpld3.save_d3_html(fig, gp.html_file_output) mpld3.show(fig) except: pass # FRAGILE! convert to Bokeh format # better to use direct Bokeh renderer try: if (gp.convert_matplotlib_to_bokeh == True): from bokeh.plotting import output_file, show from bokeh import mpl output_file(gp.html_file_output) show(mpl.to_bokeh()) except: pass # FRAGILE! convert matplotlib chart to Plotly format # recommend using AdapterCufflinks instead to directly plot to Plotly try: import plotly.plotly as py import plotly import plotly.tools as tls if gp.convert_matplotlib_to_plotly == True: plotly.tools.set_credentials_file(username = gp.plotly_username, api_key = gp.plotly_api_key) py_fig = tls.mpl_to_plotly(fig, strip_style = True) plot_url = py.plot_mpl(py_fig, filename = gp.plotly_url) except: pass # display in matplotlib window try: if GraphicsConstants.plotfactory_silent_display == True: return fig elif gp.silent_display == False: plt.show() else: return fig except: pass
import numpy as np import pandas as pd from bokeh import mpl from bokeh.plotting import output_file, show ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD')) df = df.cumsum() df.plot(legend=False) output_file("dataframe.html") show(mpl.to_bokeh())
# You have several ways to input the colors: # colors = ['r','g','b','c','y','m','k'] # colors = ['red','green','blue','cyan','yellow','magenta','black'] # colors = ['#ff0000', '#008000', '#0000ff', '#00bfbf', '#bfbf00', '#bf00bf', '#000000'] # colors = [(1.0, 0.0, 0.0, 1.0), (0.0, 0.5, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0), (0.0, 0.75, 0.75, 1.0), # (0.75, 0.75, 0, 1.0), (0.75, 0, 0.75, 1.0), (0.0, 0.0, 0.0, 1.0)] colors = ['r', 'g', 'b', 'c', 'y', 'm', 'k'] widths = [5, 10, 20, 40, 20, 10, 5] segments = make_segments(x, y) lc = LineCollection(segments, colors=colors, linewidth=widths, alpha=alpha) ax = plt.gca() ax.add_collection(lc) return lc # Colored sine wave x = np.linspace(0, 4 * np.pi, 100) y = np.sin(x) colorline(x, y) plt.title("MPL support for ListCollection in Bokeh") plt.xlim(x.min(), x.max()) plt.ylim(-1.0, 1.0) mpl.to_bokeh(name="listcollection")
def sample_distribution_for_genes(dataset_identifier, genes, title="", samples=None, unit="zscore", chart_type="heat", chart_rendering="html"): try: generator = None convert = False tooltip = False sns.set(style="whitegrid") #get path to HDF store from config file path_to_store = APP_CONFIG["application_files_location"] + APP_CONFIG["application_store_name"] print("path to store " + path_to_store) print(genes) #get data set as a pandas frame dataset = dr.get_data_frame_from_hdf(dataset_identifier, path_to_store) tooltip = None #filter selected genes gene_list = dataset.loc[genes, :] labels = list(gene_list.columns) #matplotlib settings ax = None fig = None #heatmap #html = dynamic plot #pdf = pdf file if chart_type == "heat": if chart_rendering == "html": print("bokeh heatmap") sns.set() title += " heatmap" generator = "bokeh" print("sns heatmap") fig = HeatMap(gene_list.dropna(), title=title) elif chart_rendering == "pdf": plt.switch_backend('Agg') title += " heatmap pdf" sns.set_context("paper", font_scale=0.8) generator = "matplot" ax = sns.heatmap(gene_list) #adapt label fontsize for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(2.0) # tick.label.set print("axis loaded") print("heatmap with bokeh") elif chart_type == "box": #boxplot charts title += " boxplot" generator = "bokeh" # convert = True TOOLS = "resize,crosshair,pan,wheel_zoom,box_zoom,reset,previewsave,hover" print("creating box plot") # new_z_set = pd.DataFrame(stats.zscore(gene_list), index=gene_list.index, columns=gene_list.columns) t_genes = gene_list.transpose() # sns.boxplot(t_genes, color="coolwarm_r", names=t_genes.columns) fig = BoxPlot(t_genes, legend=True, tools=TOOLS) hover = fig.select(dict(type=HoverTool)) hover.tooltips = [ ("sample", "$index") ] elif chart_type == "scatter": if chart_rendering == "html": title += " scatter" generator = "bokeh" # tooltip = True TOOLS = "resize, crosshair, pan, wheel_zoom, box_zoom,reset, previewsave, hover" fig = bpl.figure(title=title, tools=TOOLS) current_palette = sns.color_palette() i = 0 colors = bp.Spectral10 # fig.scatter(dc, dc["index"]) for e in gene_list.iterrows(): val = [v for v in e[1]] idx = range(0, len(val)) col_data_source = ColumnDataSource(dict( x=idx, y=val, sample=gene_list.columns[idx], )) fig.scatter('x', 'y', color=colors[i], legend=e[0], source=col_data_source) i += 1 hover = fig.select(dict(type=HoverTool)) hover.tooltips = [ ("sample", "@sample"), ("count", "$y") ] elif chart_rendering == "pdf": plt.switch_backend('PDF') sns.color_palette("deep") title += " scatter pdf" generator = "matplot" print("starting with matplot") transposed_data = gene_list.transpose() ax = transposed_data.plot(style='o') legend = plt.legend(frameon=1) frame = legend.get_frame() frame.set_edgecolor('blue') coll_len = len(gene_list.columns) for idx, gene in enumerate(gene_list.index): for x, y in zip(range(0, coll_len), gene_list.iloc[idx, :]): if y > gene_list.iloc[idx, :].quantile(0.99): ax.annotate(labels[x], xy=(x, y), textcoords='data') # grid.add_legend(labels) print("plotted with matplot") if ax is not None: if generator == "matplot" and (title is not None): ax.set_title(title) elif generator == "matplot" and ax is not None: ax.set_title(title) if generator == "matplot": fig = plt.gcf() if convert is True and generator == "bokeh": fig = plt.gcf() fig = mpl.to_bokeh(fig) return {"generator": generator, "chart": fig} except BaseException as e: print(e.__str__())
def exoctk_tot_results(): exo_dict = ExoCTK.tot.transit_obs.load_exo_dict() inst_dict = ExoCTK.tot.transit_obs.load_mode_dict('WFC3 G141') # Get the input from the form exo_dict['star']['hmag'] = float( request.form['hmag']) # H-band magnitude of the system exo_dict['planet']['exopath'] = request.form[ 'exopath'] # filename for model spectrum [wavelength, flux] exo_dict['planet']['w_unit'] = request.form[ 'w_unit'] # wavelength unit (um or nm) exo_dict['planet']['f_unit'] = request.form[ 'f_unit'] # flux unit (fp/f* or (rp/r*)^2) exo_dict['planet'][ 'depth'] = 4.0e-3 # Approximate transit/eclipse depth for plotting purposes exo_dict['planet']['i'] = float( request.form['i']) # Orbital inclination in degrees exo_dict['planet']['ars'] = float( request.form['ars'] ) # Semi-major axis in units of stellar radii (a/R*) exo_dict['planet']['period'] = float( request.form['period']) # Orbital period in days # Detector and Observation inputs (Make these form inputs!) exo_dict['calculation'] = 'scale' inst_dict['configuration']['detector'][ 'subarray'] = 'GRISM256' # Subarray size, GRISM256 or GRISM512 inst_dict['configuration']['detector']['nsamp'] = 10 # WFC3 NSAMP, 1..15 inst_dict['configuration']['detector'][ 'samp_seq'] = 'SPARS5' # WFC3 SAMP-SEQ, SPARS5, SPARS10, or SPARS25 exo_dict['observation'][ 'transit_duration'] = 4170 # Full transit/eclipse duration in seconds exo_dict['observation']['norbits'] = 4 # Number of HST orbits per visit exo_dict['observation']['noccultations'] = 5 # Number of transits/eclipses exo_dict['observation'][ 'nchan'] = 15 # Number of spectrophotometric channels exo_dict['observation'][ 'scanDirection'] = 'Forward' # Spatial scan direction, Forward or Round Trip exo_dict['observation'][ 'schedulability'] = '30' # % time HST can observe target (30 or 100) # Run PandExo deptherr, rms, ptsOrbit = ExoCTK.tot.transit_obs.run_pandexo( exo_dict, inst_dict, output_file='wasp43b_G141.p') # Plot the model spectrum with simpulated data and uncertainties specfile = exo_dict['planet']['exopath'] w_unit = exo_dict['planet']['w_unit'] grism = inst_dict['configuration']['instrument']['disperser'] nchan = exo_dict['observation']['nchan'] binspec = ExoCTK.tot.transit_obs.plot_PlanSpec( specfile, w_unit, grism, deptherr, nchan, smooth=10, labels=['Model Spectrum', 'Simulated Obs.']) # Make the matplotlib plot into a Bokeh plot plt.savefig('static/plots/sim.png') sim_plot = mpl.to_bokeh(plt.gcf()) output_file('test_sim.html') save(sim_plot) plt.close() xmin, xmax = (1.125, 1.650) ymin, ymax = (np.min(binspec) - 2 * deptherr, np.max(binspec) + 2 * deptherr) sim_plot.y_range = Range1d(ymin, ymax) sim_plot.x_range = Range1d(xmin, 6) # sim_plot.y_axis_label = 'Wavelength (micron)' sim_script, sim_plot = components(sim_plot) # Plot the transit curves numorbits = exo_dict['observation']['norbits'] depth = exo_dict['planet']['depth'] inc = exo_dict['planet']['i'] aRs = exo_dict['planet']['ars'] period = exo_dict['planet']['period'] windowSize = 20 # observation start window size in minutes minphase, maxphase = ExoCTK.tot.transit_obs.calc_StartWindow('eclipse', rms, ptsOrbit, numorbits, depth, inc, aRs, period, windowSize, ecc=0, w=90.) # Make the matplotlib plot into a Bokeh plot plt.savefig('static/plots/obs.png') obs_plot = mpl.to_bokeh(plt.gcf()) output_file('test_obs.html') save(obs_plot) plt.close() obs_script, obs_plot = components(obs_plot) exo_dict['minphase'] = round(minphase, 4) exo_dict['maxphase'] = round(maxphase, 4) sim = open('test_sim.html') lines = sim.readlines() sim_html = "".join(lines) sim.close() obs = open('test_obs.html') lines = obs.readlines() obs_html = "".join(lines) print(obs_html) html_dict = {'sim': sim_html, 'obs': obs_html} return render_template('tot_results.html', exo_dict=exo_dict, html_dict=html_dict)
import numpy as np import pandas as pd from bokeh import mpl from bokeh.plotting import show ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD')) df = df.cumsum() df.plot(legend=False) show(mpl.to_bokeh(name="dataframe"))
# demo inspired by: http://matplotlib.org/examples/pylab_examples/stem_plot.html from bokeh import mpl from bokeh.plotting import output_file, show import matplotlib.pyplot as plt import numpy as np x = np.linspace(0.1, 2*np.pi, 10) markerline, stemlines, baseline = plt.stem(x, np.cos(x), '-.') plt.setp(markerline, 'markerfacecolor', 'b') plt.setp(baseline, 'color', 'r', 'linewidth', 2) output_file("mpl_stem.html", title="mpl_stem.py example") show(mpl.to_bokeh(tools='pan, wheel_zoom, crosshair'))
rasterized=True, linestyle=next(linecycler)) legend = ax1.legend() ax1.legend(loc=0) ax1.minorticks_on() ax1.set_ylim((0, np.max(new_sigma))) ax1.set_xlim((0.1, 3.1)) # ax1.set_title(r'$\sigma({0})={1:.1f}\%$'.format(str(label[key_y]), np.abs(sigma_just_CMB_y / fid[key_y] * 100.))) ax1.set_ylabel(r'sigma(' + label[key_y] + r')') ax1.set_xlabel(r'prior/sigma(x) old') plt.title(r'Prior results on ' + label[key_y]) # ============================================ # FINALLY SAVE # ============================================ # ============================================ # ============================================ output_file("subplots.html") save(mpl.to_bokeh()) plt.savefig(base_dir + 'data/{}/run{}/output/prior_{}_snow_mass.pdf'.format( data_type, str(run_idx), str(key_y)), dpi=400, papertype='Letter', format='pdf', transparent=True, bbox_inches='tight') plt.close()
plt.subplot(221) plt.plot(x, y1, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.ylabel('I', fontsize=20) plt.subplot(222) plt.plot(x, y2, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), yticklabels=[], xticks=(0, 10, 20)) plt.ylabel('II', fontsize=20) plt.subplot(223) plt.plot(x, y3, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.ylabel('III', fontsize=20) plt.setp(plt.gca(), yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.subplot(224) xfit = np.array([np.amin(x4), np.amax(x4)]) plt.plot(x4, y4, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), yticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.ylabel('IV', fontsize=20) # We create the figure in matplotlib and then we "pass it" to Bokeh show(mpl.to_bokeh(name="subplots"))
numpoly, numverts = 100, 4 centers = 100 * (np.random.random((numpoly, 2)) - 0.5) offsets = 10 * (np.random.random((numverts, numpoly, 2)) - 0.5) verts = centers + offsets verts = np.swapaxes(verts, 0, 1) # In your case, "verts" might be something like: # verts = zip(zip(lon1, lat1), zip(lon2, lat2), ...) # If "data" in your case is a numpy array, there are cleaner ways to reorder # things to suit. facecolors = ['red', 'green', 'blue', 'cyan', 'yellow', 'magenta', 'black'] edgecolors = ['cyan', 'yellow', 'magenta', 'black', 'red', 'green', 'blue'] widths = [5, 10, 20, 10, 5] ax = plt.axes() # Make the collection and add it to the plot. col = PolyCollection(verts, facecolor=facecolors, edgecolor=edgecolors, linewidth=widths, linestyle='--', alpha=0.5) ax.add_collection(col) plt.xlim([-60, 60]) plt.ylim([-60, 60]) plt.title("MPL-PolyCollection support in Bokeh") mpl.to_bokeh(name="polycollection")
import numpy as np import pandas as pd import seaborn as sns import matplotlib as mplc import matplotlib.pyplot as plt from bokeh import mpl from bokeh.plotting import show # Generate the pandas dataframe data = np.random.multivariate_normal([0, 0], [[1, 2], [2, 20]], size=100) data = pd.DataFrame(data, columns=["X", "Y"]) mplc.rc("figure", figsize=(6, 6)) # Just plot seaborn kde sns.kdeplot(data, cmap="BuGn_d") plt.title("Seaborn kdeplot in bokeh.") show(mpl.to_bokeh(name="kde"))
def update_frame(self, key, ranges=None): if key in self.hmap: self.mplplot.update_frame(key, ranges) self.handles['plot'] = mpl.to_bokeh(self.mplplot.state)
# a "waterfall" plot or a "stagger" plot. nverts = 60 ncurves = 20 offs = (0.1, 0.0) rs = np.random.RandomState([12345678]) yy = np.linspace(0, 2 * np.pi, nverts) ym = np.amax(yy) xx = (0.2 + (ym - yy) / ym) ** 2 * np.cos(yy - 0.4) * 0.5 segs = [] for i in range(ncurves): xxx = xx + 0.02 * rs.randn(nverts) curve = list(zip(xxx, yy * 100)) segs.append(curve) colors = [(1.0, 0.0, 0.0, 1.0), (0.0, 0.5, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0), (0.0, 0.75, 0.75, 1.0), (0.75, 0.75, 0, 1.0), (0.75, 0, 0.75, 1.0), (0.0, 0.0, 0.0, 1.0)] col = LineCollection(segs, linewidth=5, offsets=offs) ax = plt.axes() ax.add_collection(col, autolim=True) col.set_color(colors) ax.set_title('Successive data offsets') fig = plt.gcf() mpl.to_bokeh(name="lc_offsets")
import numpy as np import pandas as pd from bokeh import mpl ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() p = ts.plot() mpl.to_bokeh(name="series")
from ggplot import * from bokeh import mpl from bokeh.plotting import show import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({ "x": range(100), "y": np.random.choice([-1, 1], 100) }) df.y = df.y.cumsum() g = ggplot(aes(x='x', y='y'), data=df) + \ geom_step() g.draw() plt.title("Step ggplot-based plot in Bokeh.") show(mpl.to_bokeh(name="step"))
rs = np.random.RandomState([12345678]) yy = np.linspace(0, 2 * np.pi, nverts) ym = np.amax(yy) xx = (0.2 + (ym - yy) / ym) ** 2 * np.cos(yy - 0.4) * 0.5 segs = [] for i in range(ncurves): xxx = xx + 0.02 * rs.randn(nverts) curve = list(zip(xxx, yy * 100)) segs.append(curve) colors = [ (1.0, 0.0, 0.0, 1.0), (0.0, 0.5, 0.0, 1.0), (0.0, 0.0, 1.0, 1.0), (0.0, 0.75, 0.75, 1.0), (0.75, 0.75, 0, 1.0), (0.75, 0, 0.75, 1.0), (0.0, 0.0, 0.0, 1.0), ] col = LineCollection(segs, linewidth=5, offsets=offs) ax = plt.axes() ax.add_collection(col, autolim=True) col.set_color(colors) ax.set_title("Successive data offsets") fig = plt.gcf() show(mpl.to_bokeh(name="lc_offsets"))
plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.ylabel('I', fontsize=20) plt.subplot(222) plt.plot(x, y2, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), xticklabels=[], yticks=(4, 8, 12), yticklabels=[], xticks=(0, 10, 20)) plt.ylabel('II', fontsize=20) plt.subplot(223) plt.plot(x, y3, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.ylabel('III', fontsize=20) plt.setp(plt.gca(), yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.subplot(224) xfit = np.array([np.amin(x4), np.amax(x4)]) plt.plot(x4, y4, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), yticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.ylabel('IV', fontsize=20) # We create the figure in matplotlib and then we "pass it" to Bokeh show(mpl.to_bokeh(name="subplots"))
def plot_2d_graph(self, data_frame, gp, chart_type): if gp is None: gp = GraphProperties() if gp.chart_type is None and chart_type is None: chart_type = 'line' if gp.resample is not None: data_frame = data_frame.asfreq(gp.resample) self.apply_style_sheet(gp) # create figure & add a subplot fig = plt.figure(figsize=((gp.width * gp.scale_factor) / gp.dpi, (gp.height * gp.scale_factor) / gp.dpi), dpi=gp.dpi) ax = fig.add_subplot(111) if gp.x_title != '': ax.set_xlabel(gp.x_title) if gp.y_title != '': ax.set_ylabel(gp.y_title) plt.xlabel(gp.x_title) plt.ylabel(gp.y_title) fig.suptitle(gp.title, fontsize=14 * gp.scale_factor) # format Y axis y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) ax.yaxis.set_major_formatter(y_formatter) # create a second y axis if necessary ax2 = [] if gp.y_axis_2_series != []: ax2 = ax.twinx() # do not use a grid with multiple y axes ax.yaxis.grid(False) ax2.yaxis.grid(False) # matplotlib 1.5 try: cyc = matplotlib.rcParams['axes.prop_cycle'] color_cycle = [x['color'] for x in cyc] except KeyError: # pre 1.5 pass # color_cycle = matplotlib.rcParams['axes.color_cycle'] bar_ind = np.arange(0, len(data_frame.index)) # for bar charts, create a proxy x-axis (then relabel) xd, bar_ind, has_bar, no_of_bars = self.get_bar_indices( data_frame, gp, chart_type, bar_ind) # plot the lines (using custom palettes as appropriate) try: # get all the correct colors (and construct gradients if necessary eg. from 'blues') color_spec = self.create_color_list(gp, data_frame) # for stacked bar yoff_pos = np.zeros(len(data_frame.index.values) ) # the bottom values for stacked bar chart yoff_neg = np.zeros(len(data_frame.index.values) ) # the bottom values for stacked bar chart zeros = np.zeros(len(data_frame.index.values)) # for bar chart bar_space = 0.2 bar_width = (1 - bar_space) / (no_of_bars) bar_index = 0 has_matrix = False # some lines we should exclude from the color and use the default palette for i in range(0, len(data_frame.columns.values)): if gp.chart_type is not None: if isinstance(gp.chart_type, list): chart_type = gp.chart_type[i] else: chart_type = gp.chart_type if chart_type == 'heatmap': # TODO experimental! # ax.set_frame_on(False) ax.pcolor(data_frame, cmap=plt.cm.Blues, alpha=0.8) # plt.colorbar() has_matrix = True break label = str(data_frame.columns[i]) ax_temp = self.get_axis(ax, ax2, label, gp.y_axis_2_series) yd = data_frame.ix[:, i] if color_spec[i] is None: color_spec[i] = color_cycle[i % len(color_cycle)] if (chart_type == 'line'): linewidth_t = self.get_linewidth(label, gp.linewidth, gp.linewidth_2, gp.linewidth_2_series) if linewidth_t is None: linewidth_t = matplotlib.rcParams['axes.linewidth'] ax_temp.plot(xd, yd, label=label, color=color_spec[i], linewidth=linewidth_t) elif (chart_type == 'bar'): # for multiple bars we need to allocate space properly bar_pos = [ k - (1 - bar_space) / 2. + bar_index * bar_width for k in range(0, len(bar_ind)) ] ax_temp.bar(bar_pos, yd, bar_width, label=label, color=color_spec[i]) bar_index = bar_index + 1 elif (chart_type == 'stacked'): bar_pos = [ k - (1 - bar_space) / 2. + bar_index * bar_width for k in range(0, len(bar_ind)) ] yoff = np.where(yd > 0, yoff_pos, yoff_neg) ax_temp.bar(bar_pos, yd, label=label, color=color_spec[i], bottom=yoff) yoff_pos = yoff_pos + np.maximum(yd, zeros) yoff_neg = yoff_neg + np.minimum(yd, zeros) # bar_index = bar_index + 1 elif (chart_type == 'scatter'): ax_temp.scatter(xd, yd, label=label, color=color_spec[i]) if gp.line_of_best_fit is True: self.trendline(ax_temp, xd.values, yd.values, order=1, color=color_spec[i], alpha=1, scale_factor=gp.scale_factor) # format X axis self.format_x_axis(ax, data_frame, gp, has_bar, bar_ind, has_matrix) except: pass if gp.display_source_label == True: ax.annotate('Source: ' + gp.source, xy=(1, 0), xycoords='axes fraction', fontsize=7 * gp.scale_factor, xytext=(-5 * gp.scale_factor, 10 * gp.scale_factor), textcoords='offset points', ha='right', va='top', color=gp.source_color) if gp.display_brand_label == True: self.create_brand_label(ax, anno=gp.brand_label, scale_factor=gp.scale_factor) leg = [] leg2 = [] loc = 'best' # if we have two y-axis then make sure legends are in opposite corners if ax2 != []: loc = 2 try: leg = ax.legend(loc=loc, prop={'size': 10 * gp.scale_factor}) leg.get_frame().set_linewidth(0.0) leg.get_frame().set_alpha(0) if ax2 != []: leg2 = ax2.legend(loc=1, prop={'size': 10 * gp.scale_factor}) leg2.get_frame().set_linewidth(0.0) leg2.get_frame().set_alpha(0) except: pass try: if gp.display_legend is False: if leg != []: leg.remove() if leg2 != []: leg.remove() except: pass try: plt.savefig(gp.file_output, transparent=False) except: pass ####### various matplotlib converters are unstable # convert to D3 format with mpld3 try: # output matplotlib charts externally to D3 based libraries import mpld3 if gp.display_mpld3 == True: mpld3.save_d3_html(fig, gp.html_file_output) mpld3.show(fig) except: pass # FRAGILE! convert to Bokeh format # better to use direct Bokeh renderer try: if (gp.convert_matplotlib_to_bokeh == True): from bokeh.plotting import output_file, show from bokeh import mpl output_file(gp.html_file_output) show(mpl.to_bokeh()) except: pass # FRAGILE! convert matplotlib chart to Plotly format # recommend using AdapterCufflinks instead to directly plot to Plotly try: import plotly.plotly as py import plotly import plotly.tools as tls if gp.convert_matplotlib_to_plotly == True: plotly.tools.set_credentials_file(username=gp.plotly_username, api_key=gp.plotly_api_key) py_fig = tls.mpl_to_plotly(fig, strip_style=True) plot_url = py.plot_mpl(py_fig, filename=gp.plotly_url) except: pass # display in matplotlib window try: if Constants.plotfactory_silent_display == True: pass elif gp.silent_display == False: plt.show() except: pass
def load_spectra(): #'/Users/guillaumeshippee/Desktop/splat-master/reference/Spectra/10001_10443.fits' #change if request.method == 'GET': return render_template('input.html', error='') else: # for k in list(request.form.keys()): # print(k,request.form[k]) # search by file "upload" if request.form['submit'] == 'Load File': try: path = request.form['path'] sp = splat.Spectrum(file=str(path)) sp = [sp] except: return render_template('input.html', error = "\n\nProblem with file upload button") # search by file path specification if request.form['submit'] == 'Load File ': try: path = request.form['path'] sp = splat.Spectrum(file=str(path)) sp = [sp] except: return render_template('input.html', error = "\n\nProblem with file path specification") # search by spectrum key if request.form['submit'] == 'Load by ID': try: sp = splat.Spectrum(int(str(request.form['key']))) sp = [sp] except: return render_template('input.html', error = "\n\nProblem with key specification") # search by date observed if request.form['submit'] == 'Load by Date': try: sp = splat.getSpectrum(date = str(request.form['date'])) except: return render_template('input.html', error = "\n\nProblem with key specification") # search by shortname elif request.form['submit'] == 'Load by Shortname': try: sp = splat.getSpectrum(shortname = str(request.form['shortname'])) except: return render_template('input.html', error = "\n\nProblem with specifying file by shortname") # search by name elif request.form['submit'] == 'Load by Name': try: sp = splat.getSpectrum(name = str(request.form['name'])) except: return render_template('input.html', error = "\n\nProblem with specifying file by name") # search by options elif request.form['submit'] == 'Load by Options': sp1 = request.form['sp1'] sp2 = request.form['sp2'] mag1 = request.form['mag1'] mag2 = request.form['mag2'] if sp2 == '': sp = sp1 elif sp1 == '': sp2 = sp1 elif sp1 == '' and sp2 == '': sp = '' else: sp = [sp1, sp2] if mag2 == '': mag = mag1 elif sp1 == '': mag2 = mag1 elif sp1 == '' and sp2 == '': mag = '' else: mag = [mag1, mag2] kwargs = {'spt': sp, 'jmag' : mag, 'snr' : request.form['snr'], 'date' : request.form['date'] } kwargs = {k: v for k, v in kwargs.items() if v} try: sp = splat.getSpectrum(**kwargs) except: return render_template('input.html', error = "\n\nProblem with option search") # lucky pull elif request.form['submit'] == 'Get Lucky!': sp = splat.getSpectrum(lucky=True) if len(sp) == 0: return render_template('input.html', error = "\n\nNo spectra matched search constratins") try: tab = [] for s in sp: spectral_type = splat.classifyByStandard(s)[0] mpl_fig = splat.plotSpectrum(s, web=True, uncertainty = True, mdwarf=True)[0] bokehfig = mpl.to_bokeh(fig=mpl_fig) bokehfig.set(x_range=Range1d(.8,2.4),y_range=Range1d(0,s.fluxMax().value*1.2)) # sys.stdout = open("out1.txt", "w") # sys.stdout = sys.__stdout__ # with open("out1.txt", "r") as f: # content = f.read() content = s.info(printout=False) # print(content) p = Paragraph(text=content) widget = VBox(bokehfig, p) tab.append(Panel(child=widget, title=str(s.name))) # tab.append(Panel(child=widget, title=str(spectral_type)+ " Star")) plottabs = Tabs(tabs= tab) script, div_dict = components({"plot" : plottabs}) except: return render_template('input.html', error = "\n\nProblem Plotting Spectra") return render_template('out.html', star_type = spectral_type, script=script, div=div_dict)
def make_violin_plot(x, y, hue, data, plot_type="factor", palette="GnBu", width=750, height=500): data = data[[x, y, hue]] sns_palette = sns.color_palette(palette, 2) sns.set_style("whitegrid") if plot_type == "factor": violin_plot_sns = sns.factorplot(x=x, y=y, hue=hue, data=data, kind="violin", palette=sns_palette) else: violin_plot_sns = sns.violinplot(x=x, y=y, hue=hue, data=data, palette=sns_palette, split=True, scale="area", inner="box", orient="v", bw=.15, responsive=True) violin_plot = mpl.to_bokeh() violin_plot.toolbar_location = "above" violin_plot.toolbar_sticky = False violin_plot.grid.grid_line_color = "SlateGray" violin_plot.grid.grid_line_alpha = .5 violin_plot.grid.minor_grid_line_color = "SlateGray" violin_plot.grid.minor_grid_line_alpha = .2 violin_plot.plot_height = height violin_plot.plot_width = width if "amount" in y: violin_plot.title.text = "Fare Violin Plot" violin_plot.yaxis[0].formatter = NumeralTickFormatter(format="$ 0.00") if "distance" in y: violin_plot.title.text = "Distance Violin Plot" violin_plot.yaxis[0].formatter = PrintfTickFormatter( format="%5.2f miles") def day_ticker(): days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] if abs(int(round(tick)) - tick) < .05: return days[int(round(tick))] else: return "" def month_ticker(): months = [ "January", "February", "March", "April", "May", "June", "July" ] if abs(int(round(tick)) - tick) < .05: return months[int(round(tick))] else: return "" if "day" in x: violin_plot.xaxis[0].formatter = FuncTickFormatter.from_py_func( day_ticker) if "month" in x: violin_plot.xaxis[0].formatter = FuncTickFormatter.from_py_func( month_ticker) return violin_plot
import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from bokeh import mpl from bokeh.plotting import show # In order to efficiently plot many lines in a single set of axes, # add the lines all at once. Here is a simple example showing how it is done. N = 50 x = np.arange(N) # Here are many sets of y to plot vs x ys = [x + i for i in x] colors = ['#ff0000', '#008000', '#0000ff', '#00bfbf', '#bfbf00', '#bf00bf', '#000000'] line_segments = LineCollection([list(zip(x, y)) for y in ys], color=colors, linewidth=(0.5, 1, 1.5, 2), linestyle='dashed') ax = plt.axes() ax.add_collection(line_segments) ax.set_title('Line Collection with dashed colors') show(mpl.to_bokeh(name="lc_dashed"))
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from bokeh import mpl from bokeh.plotting import show # We generated random data data = 1 + np.random.randn(20, 6) # And then just call the violinplot from Seaborn sns.violinplot(data, color="Set3") plt.title("Seaborn violin plot in bokeh.") show(mpl.to_bokeh(name="violin"))
from ggplot import * from bokeh import mpl import matplotlib.pyplot as plt g = ggplot(diamonds, aes(x='price', color='cut')) + \ geom_density() g.draw() plt.title("Density ggplot-based plot in Bokeh.") mpl.to_bokeh(name="density")
from ggplot import * from bokeh import mpl import matplotlib.pyplot as plt g = ggplot(diamonds, aes(x='price', color='cut')) + \ geom_density() g.draw() plt.title("xkcd-ggplot-mpl based plot in Bokeh.") mpl.to_bokeh(name="xkcd_density", xkcd=True)
def plot_2d_graph(self, data_frame, gp, chart_type): if gp.resample is not None: data_frame = data_frame.asfreq(gp.resample) # set the matplotlib style sheet & defaults matplotlib.rcdefaults() # first search PyThalesians styles, then try matplotlib try: plt.style.use(Constants().plotfactory_pythalesians_style_sheet[gp.style_sheet]) except: plt.style.use(gp.style_sheet) matplotlib.rcParams.update({'font.size': matplotlib.rcParams['font.size'] * gp.scale_factor}) # create figure & add a subplot fig = plt.figure(figsize = ((gp.width * gp.scale_factor)/gp.dpi, (gp.height * gp.scale_factor)/gp.dpi), dpi = gp.dpi) ax = fig.add_subplot(111) # format Y axis y_formatter = matplotlib.ticker.ScalarFormatter(useOffset = False) ax.yaxis.set_major_formatter(y_formatter) if gp.x_title != '': ax.set_xlabel(gp.x_title) if gp.y_title != '': ax.set_ylabel(gp.y_title) # create a second y axis if necessary ax2 = [] if gp.y_axis_2_series != []: ax2 = ax.twinx() # do not use a grid with multiple y axes ax.yaxis.grid(False) ax2.yaxis.grid(False) color_cycle = matplotlib.rcParams['axes.color_cycle'] bar_ind = np.arange(0, len(data_frame.index)) xd, bar_ind, has_bar, no_of_bars = self.get_bar_indices(data_frame, gp, chart_type, bar_ind) # plot the lines (using custom palettes as appropriate) try: # get all the correct colors (and construct gradients if necessary eg. from 'blues') color_spec = self.create_color_list(gp, data_frame) # for stacked bar yoff = np.zeros(len(data_frame.index.values)) # the bottom values for stacked bar chart # for bar chart # bar_ind = np.arange(len(data_frame.index)) # has_bar = False bar_space = 0.2 bar_width = (1 - bar_space) / (no_of_bars) bar_index = 0 # some lines we should exclude from the color and use the default palette for i in range(0, len(data_frame.columns.values)): if chart_type is not None: if gp.chart_type is not None: if isinstance(gp.chart_type, list): chart_type = gp.chart_type[i] else: chart_type = gp.chart_type label = str(data_frame.columns[i]) ax_temp = self.get_axis(ax, ax2, label, gp.y_axis_2_series) yd = data_frame.ix[:,i] if (chart_type == 'line'): linewidth_t = self.get_linewidth(label, gp.linewidth, gp.linewidth_2, gp.linewidth_2_series) if linewidth_t is None: linewidth_t = matplotlib.rcParams['axes.linewidth'] ax_temp.plot(xd, yd, label = label, color = color_spec[i], linewidth = linewidth_t) elif(chart_type == 'bar'): bar_pos = [k - (1 - bar_space) / 2. + bar_index * bar_width for k in range(0,len(bar_ind))] if color_spec[i] is not None: ax_temp.bar(bar_pos, yd, bar_width, label = label, color = color_spec[i]) else: ax_temp.bar(bar_pos, yd, bar_width, label = label, color = color_cycle[i % len(color_cycle)]) bar_index = bar_index + 1 # bar_ind = bar_ind + bar_width has_bar = True elif(chart_type == 'stacked'): ax_temp.bar(xd, yd, label = label, color = color_spec[i], bottom = yoff) yoff = yoff + yd has_bar = True elif(chart_type == 'scatter'): ax_temp.scatter(xd, yd, label = label, color = color_spec[i]) if gp.line_of_best_fit is True: self.trendline(ax_temp, xd.values, yd.values, order=1, color= color_spec[i], alpha=1, scale_factor = gp.scale_factor) # format X axis self.format_x_axis(ax, data_frame, gp, has_bar, bar_ind) except: pass plt.xlabel(gp.x_title) plt.ylabel(gp.y_title) fig.suptitle(gp.title, fontsize = 14 * gp.scale_factor) if gp.display_source_label == True: ax.annotate('Source: ' + gp.source, xy = (1, 0), xycoords='axes fraction', fontsize=7 * gp.scale_factor, xytext=(-5 * gp.scale_factor, 10 * gp.scale_factor), textcoords='offset points', ha='right', va='top', color = gp.source_color) if gp.display_brand_label == True: self.create_brand_label(ax, anno = gp.brand_label, scale_factor = gp.scale_factor) leg = [] leg2 = [] loc = 'best' # if we have two y-axis then make sure legends are in opposite corners if ax2 != []: loc = 2 try: leg = ax.legend(loc = loc, prop={'size':10 * gp.scale_factor}) leg.get_frame().set_linewidth(0.0) leg.get_frame().set_alpha(0) if ax2 != []: leg2 = ax2.legend(loc = 1, prop={'size':10 * gp.scale_factor}) leg2.get_frame().set_linewidth(0.0) leg2.get_frame().set_alpha(0) except: pass try: if gp.display_legend is False: if leg != []: leg.remove() if leg2 != []: leg.remove() except: pass try: plt.savefig(gp.file_output, transparent=False) except: pass ####### various matplotlib converters are unstable # convert to D3 format with mpld3 try: if gp.display_mpld3 == True: mpld3.save_d3_html(fig, gp.html_file_output) mpld3.show(fig) except: pass # FRAGILE! convert to Bokeh format # better to use direct Bokeh renderer try: if (gp.convert_matplotlib_to_bokeh == True): from bokeh.plotting import output_file, show from bokeh import mpl output_file(gp.html_file_output) show(mpl.to_bokeh()) except: pass # FRAGILE! convert matplotlib chart to Plotly format # recommend using AdapterCufflinks instead to directly plot to Plotly try: if gp.convert_matplotlib_to_plotly == True: plotly.tools.set_credentials_file(username = gp.plotly_username, api_key = gp.plotly_api_key) py_fig = tls.mpl_to_plotly(fig, strip_style = True) plot_url = py.plot_mpl(py_fig, filename = gp.plotly_url) except: pass # display in Matplotlib try: if gp.silent_display == False: plt.show() except: pass