def create_fuelsaved_plot(): """ Creates a plot of the fuel saved using PT miles and fuel data, and average mpg of personal vehicles over the years. """ temp1 = combine_for_correlation(df1=get_fuel_usage(), df2=get_bus_miles()) temp2 = combine_for_correlation(df1=temp1, df2=get_car_economy()) temp2.loc[2007, 'Bus Miles'] = temp2.loc[2007, 'Bus Miles']*1e3 temp2['Car Fuel Usage'] = temp2['Bus Miles'].div( temp2['Real World Fuel Economy (mpg)']) plotly.offline.init_notebook_mode(connected=True) fig, ax = plt.subplots() fig.set_figheight(6) fig.set_figwidth(12) ax.set_xlabel('Years') ax.set_ylabel('Fuel Consumption (gallons)') ax.plot(temp2['Car Fuel Usage'], label='Car Fuel Usage', color='#80D9FF') ax.plot(temp2['Diesel Usage'], label='Bus Fuel Usage', color='#BFFF00') patch2 = mlines.Line2D([], [], color='#BFFF00', marker='*', markersize=15, label='Bus Fuel Usage') patch1 = mlines.Line2D([], [], color='#80D9FF', marker='*', markersize=15, label='Car Fuel Usage') # ax.legend(loc="upper right",handles=[patch1,patch2]) update = {'data': [{'fill': 'tozeroy'}]} # this updates BOTH traces now plotly_fig = tls.mpl_to_plotly(fig) plotly_fig.update(update) plotly.offline.plot(plotly_fig, filename='mpl-multi-fill')
def analysis_destination(P, m, e, data='SIH.csv'): dataset = pd.read_csv(data) x1 = dataset.loc[(dataset['Product_Name'] == P) & (dataset['Month'] == m)] y1 = x1.groupby('Day').sum() y = y1.iloc[:, 2].values x = x1.iloc[::4, 4].values #place wise anlysis des = x1.loc[x1['Destination'] == e] xp = des.iloc[:, 4].values yp = des.iloc[:, 5].values plt.figure() plt.bar(xp, yp, color='darkred') axes = plt.gca() axes.set_ylim([0, 4000]) plt.title('Destination of Supply Demand Analysis') plt.xlabel('Day') plt.ylabel('Quantity demanded') fig = plt.gcf() plotly_fig = tls.mpl_to_plotly(fig) plotly_fig['layout']['width'] = 1200 plot_div = plot(plotly_fig, output_type='div', include_plotlyjs=False) return plot_div
def analysis_seasonal(P, data='SIH.csv'): dataset = pd.read_csv(data) x3 = dataset.loc[dataset['Product_Name'] == P] ses = x3.groupby('Month').sum() ses = ses.rename(columns={'Day': 'month'}) ses.month = range(0, 12) ses['month'] = ses['month'] + 1 xs = ses.iloc[:, 1] ys = ses.iloc[:, 2] plt.figure() plt.xticks(xs) plt.bar(xs, ys, color='darkblue') plt.title('Monthly Demand') plt.xlabel('Month') plt.ylabel('Quantity demanded') fig = plt.gcf() plotly_fig = tls.mpl_to_plotly(fig) plotly_fig['layout']['width'] = 1200 # py.iplot(plotly_fig, filename='mpl-basic-bar') plot_div = plot(plotly_fig, output_type='div', include_plotlyjs=False) return plot_div
def test_normal_mpl_dates(self): datetime_format = '%Y-%m-%d %H:%M:%S' y = [1, 2, 3, 4] date_strings = [ '2010-01-04 00:00:00', '2010-01-04 10:00:00', '2010-01-04 23:00:59', '2010-01-05 00:00:00' ] # 1. create datetimes from the strings dates = [ datetime.datetime.strptime(date_string, datetime_format) for date_string in date_strings ] # 2. create the mpl_dates from these datetimes mpl_dates = date2num(dates) # make a figure in mpl fig, ax = plt.subplots() ax.plot_date(mpl_dates, y) # convert this figure to plotly's graph_objs pfig = tls.mpl_to_plotly(fig) print(date_strings) print(pfig['data'][0]['x']) # we use the same format here, so we expect equality here self.assertEqual(fig.axes[0].lines[0].get_xydata()[0][0], 7.33776000e+05) self.assertEqual(pfig['data'][0]['x'], date_strings)
def profitloss(product, filename='SIH2.csv'): dataset = pd.read_csv(filename) x_1 = dataset.loc[dataset['Product_Name'] == product] ses1 = x_1.groupby('Month').sum() ses1 = ses1.rename(columns={'Day': 'month'}) ses1.month = range(0, 12) ses1['month'] = ses1['month'] + 1 x_11 = ses1.iloc[:, 1] y_11 = ses1.iloc[:, 11] colorbar = [] for i in range(1, len(y_11) + 1): if (y_11[i] < 0): colorbar.append('red') else: colorbar.append('lightblue') plt.bar(x_11, abs(y_11), color=colorbar) plt.title('Profit/Loss, month-wise') blue_patch = mpatches.Patch(color='lightblue', label='Profit') red_patch = mpatches.Patch(color='red', label='Loss') plt.legend(handles=[blue_patch, red_patch]) fig = plt.gcf() plotly_fig = tls.mpl_to_plotly(fig) plotly_fig['layout']['width'] = 1200 plot_div = plot(plotly_fig, output_type='div', include_plotlyjs=False) pprint(plotly_fig) return plot_div
def testPlotlyfromMPL(): chart = c.Chart(2,1) chart.chartBasic(pd.Series([0,1,4,2,3,4]),(0,1), kind='line') mpl_fig = chart.fig plotly_fig = tls.mpl_to_plotly(mpl_fig) unique_url = py.plot(plotly_fig, fileopt='overwrite', auto_open=False) print(unique_url)
def update_graph(run_click, feat, channel, tier, rocktypes): if run_click: try: df = create_dataset(file) colname = [ col for col in df.columns if channel in col and feat in col ][0] groups = df.groupby(tier).groups fig, ax = plt.subplots(figsize=(10, 4.5)) ls = [df[colname][groups[x]] for x in rocktypes] for i in range(len(ls)): ls[i].plot.kde(ax=ax, label=rocktypes[i], linewidth=3) plt.title(feat + " on " + channel + " Channel", fontsize=20) if feat == "Skewness": plt.xlim((min(df[colname]), max(df[colname]))) else: plt.xlim((min(df[colname]) - 50, max(df[colname]) + 50)) plt.tick_params(labelsize=15) plt.ylabel("") plotly_fig = tls.mpl_to_plotly(fig) plotly_fig["layout"]["showlegend"] = True plotly_fig["layout"]["autosize"] = True plotly_fig["layout"]["hovermode"] = "x" plotly_fig["layout"]["legend"] = {"font": {"size": "18"}} print(type(plotly_fig)) return plotly_fig except: return {'data': [], 'layout': []}
def save_maxfig(fig, fig_name, save_plotly=False, transperent=False, frmt='png', resize=None): ''' Save figure in high resolution example: save_maxfig(fig,fig_name, save_plotly=True, transperent=True, frmt='eps', resize=[18,6]) :param fig: figure :param fig_name: file name :param save_plotly: save to plotly also :param transperent: no background :param frmt: file format :param resize: size :return: ''' # matplotlib.rcParams.update({'font.size': 40}) fig.set_size_inches(12, 12) if resize != None: fig.set_size_inches(resize[0], resize[1]) fig_name += '.' + frmt plt.savefig(fig_name, dpi=300, format=frmt) if save_plotly: # offline plotting plotly_fig = tls.mpl_to_plotly(fig) plotly_fig_name = +fig_name + '.html' plotly_fig['layout'].update(height=1500, width=800, showlegend=False) plotly.offline.plot(plotly_fig, filename=plotly_fig_name, auto_open=False) # offline ploty
def find_outliers(df, var): box_plot_figure = plt.figure(figsize=(20, 5)) df = df.copy() df.boxplot(column=var) plt.show() box_plot = tls.mpl_to_plotly(box_plot_figure) return box_plot
def find_outliers(self): for ind, v in enumerate(self.var): box_plot_figure = plt.figure() self.data.boxplot(column=v) plt.show() box_plot = tls.mpl_to_plotly(box_plot_figure) return box_plot
def plotlyUpload(table, columns, title, ylabel, limits, file_name, use_columns=columns, online=False): con = sqlite3.connect( "C:\ProgramData\ForSens\Projekte\StuttgarterBruecke\Data\Data.db3") df = pd.read_sql("SELECT * from "+table, con, parse_dates = ['TimeStep']) df.columns=columns con.close() df = df.sort_index() df = df[use_columns] fig, ax = plt.subplots() df.plot(ax=ax, x='TimeStep', legend=False) ax.set_xlabel('') ax.set_title(title) ax.set_ylim(-.5,.5) plotly_fig = tls.mpl_to_plotly(fig) plotly_fig['layout']['plot_bgcolor'] = "rgb(213, 226, 233)" plotly_fig['layout']['xaxis']['gridcolor'] = "white" plotly_fig['layout']['yaxis']['gridcolor'] = "white" plotly_fig['layout']['xaxis']['ticks'] = "" plotly_fig['layout']['yaxis']['range'] = limits plotly_fig['layout']['yaxis']['title'] = ylabel plotly_fig['layout']['autosize'] = True plotly_fig['layout']['showlegend'] = True print dir(plotly_fig.layout) if online==False: plotly.offline.plot(plotly_fig, filename=file_name) if online==True: py.plot(plotly_fig, filename=file_name, fileopt='overwrite')
def pyplot(fig, ci=True, legend=True): # Convert mpl fig obj to plotly fig obj, resize to plotly's default py_fig = tls.mpl_to_plotly(fig, resize=True) # Add fill property to lower limit line if ci == True: style1 = dict(fill='tonexty') # apply style py_fig['data'][2].update(style1) # Change color scheme to black py_fig['data'].update(dict(line=Line(color='black'))) # change the default line type to 'step' py_fig['data'].update(dict(line=Line(shape='hv'))) # Delete misplaced legend annotations py_fig['layout'].pop('annotations', None) if legend == True: # Add legend, place it at the top right corner of the plot py_fig['layout'].update( showlegend=True, legend=Legend( x=1.05, y=1 ) ) # Send updated figure object to Plotly, show result in notebook return py.iplot(py_fig)
def plot(self, *args, **kwargs): m_fig = plt.figure() plt.plot(*args, **kwargs) p_fig = tools.mpl_to_plotly(m_fig) trace = p_fig["data"][0] trace = self._update_linestyle(m_fig, trace) self.traces.append(trace)
def test_normal_mpl_dates(self): datetime_format = '%Y-%m-%d %H:%M:%S' y = [1, 2, 3, 4] date_strings = ['2010-01-04 00:00:00', '2010-01-04 10:00:00', '2010-01-04 23:00:59', '2010-01-05 00:00:00'] # 1. create datetimes from the strings dates = [datetime.datetime.strptime(date_string, datetime_format) for date_string in date_strings] # 2. create the mpl_dates from these datetimes mpl_dates = date2num(dates) # make a figure in mpl fig, ax = plt.subplots() ax.plot_date(mpl_dates, y) # convert this figure to plotly's graph_objs pfig = tls.mpl_to_plotly(fig) print(date_strings) print(pfig['data'][0]['x']) # we use the same format here, so we expect equality here self.assertEqual( fig.axes[0].lines[0].get_xydata()[0][0], 7.33776000e+05 ) self.assertEqual(pfig['data'][0]['x'], date_strings)
def plot_graph_cam(df, cam_feat_fn, cam_feat_nm, cl_feat_nm, feat, channel, tier, rock, cam_feat_val): try: ls = [ df[(df[cam_feat_nm] == x) & (df[tier] == rock)][cl_feat_nm] for x in cam_feat_val ] # for x in cam_feat_val: # ls.append(df[(df[cam_feat]==x)&(df[tier]==rock)][feat_nm]) fig, ax = plt.subplots(figsize=(10, 4.55)) for i in range(len(ls)): ls[i].plot.kde(ax=ax, label=cam_feat_val[i], linewidth=3) plt.title(feat + " on " + channel + " Channel" + " of " + rock + " with Different " + cam_feat_fn, fontsize=20) plt.tick_params(labelsize=15) plt.xlabel("Feature value", fontsize=15) plt.ylabel("Density", fontsize=15) min_val = min([min(x) for x in ls]) max_val = max([max(x) for x in ls]) ax.set_xlim([min_val, max_val]) plotly_fig = tls.mpl_to_plotly(fig) plotly_fig["layout"]["showlegend"] = True plotly_fig["layout"]["autosize"] = True plotly_fig["layout"]["hovermode"] = "x" plotly_fig["layout"]["legend"] = {"font": {"size": "18"}} return plotly_fig except: return {'data': [], 'layout': []}
def create_streamgraph_themes_dates(): # #avec les x et y x = [1, 2, 3, 4, 5] y1 = [1, 1, 2, 3, 5] y2 = [0, 4, 2, 6, 8] y3 = [1, 3, 5, 7, 9] y = np.vstack([y1, y2, y3]) labels = ["Fibonacci ", "Evens", "Odds"] fig, ax = plt.subplots() ax.stackplot(x, y1, y2, y3, baseline='weighted_wiggle', labels=labels) # ax.stackplot(x, y1, y2, y3, baseline = 'wiggle', labels=labels) ax.legend(loc='upper left') plt.show() # fig_json = json.dumps(fig) # print(fig_json) plotly_fig = tls.mpl_to_plotly(fig) # plotly_fig = tls.mpl_to_plotly(plt.gcf()) pp = pprint.PrettyPrinter(indent=4) # pprint(fig_json['coordinates']) # pprint(fig['coordinates']) pp.pprint(plotly_fig['layout']) pp.pprint(plotly_fig['data']) pp.pprint(plotly_fig['coordinates'])
def update_graph(run_click, feat, channel, tier, rocktypes): if run_click: try: df = pd.read_csv(file) colname = [ col for col in df.columns if channel in col and feat in col ][0] groups = df.groupby(tier).groups fig, ax = plt.subplots(figsize=(10, 4.5)) ls = [df[colname][groups[x]] for x in rocktypes] for i in range(len(ls)): ls[i].plot.kde(ax=ax, label=rocktypes[i], linewidth=3) plt.title(feat + " on " + channel + " Channel", fontsize=20) plt.tick_params(labelsize=15) plt.xlabel("Feature value", fontsize=15) plt.ylabel("Density", fontsize=15) min_val = min([min(x) for x in ls]) max_val = max([max(x) for x in ls]) ax.set_xlim([min_val, max_val]) plotly_fig = tls.mpl_to_plotly(fig) plotly_fig["layout"]["showlegend"] = True plotly_fig["layout"]["autosize"] = True plotly_fig["layout"]["hovermode"] = "x" plotly_fig["layout"]["legend"] = {"font": {"size": "18"}} return plotly_fig except: return {'data': [], 'layout': []}
def generate_graph(n_clicks, file_dropdown, input_dir, fsc_lower, fsc_upper, ssc_lower, ssc_upper, fl1, fsc, ssc, amplification, min_peak_size): fsc_filt = [fsc_lower, fsc_upper] ssc_filt = [ssc_lower, ssc_upper] if n_clicks > 0: mosaic = MosaicMetadata(input_dir, fsc_filt, ssc_filt, fl1, fsc, ssc, amplification, min_peak_size) data = prep_fcs(file_dropdown, mosaic) bright_outputs, plot_outputs = calc_bright_cells(data, mosaic) x_vals, y_vals, intense, freq = plot_outputs fig, ax = plt.subplots() plt.plot(intense, freq) plt.plot(x_vals, y_vals, "o", color='k') plotly_fig = tls.mpl_to_plotly(fig) graph_dict = { 'data': [go.Scatter(x=x_vals, y=y_vals, mode='lines+markers')], 'layout': { 'yaxis': { 'type': 'log' } } } return [graph_dict] else: return ['']
def plotly_pandas(df_in,x_column,num_of_x_ticks=20,plot_title=None, y_left_label=None,y_right_label=None,bar_plot=False,figsize=(16,10),number_of_ticks_display=20,use_secondary_yaxis=True): f = plot_pandas(df_in,x_column=x_column,bar_plot=bar_plot,use_secondary_yaxis=use_secondary_yaxis)#.get_figure() # list(filter(lambda s: 'get_y' in s,dir(f))) plotly_fig = tls.mpl_to_plotly(f.get_figure()) d1 = plotly_fig['data'][0] # number_of_ticks_display=20 td = list(df_in[x_column]) spacing = len(td)//number_of_ticks_display tdvals = td[::spacing] d1.x = td d_array = [d1] if len(plotly_fig['data'])>1: d2 = plotly_fig['data'][1] d2.x = td d2.xaxis = 'x' d_array.append(d2) layout = go.Layout( title='plotly' if plot_title is None else plot_title, xaxis=dict( ticktext=tdvals, tickvals=tdvals, tickangle=90, type='category'), yaxis=dict( title='y main' if y_left_label is None else y_left_label ), ) if len(d_array)>1: layout = go.Layout( title='plotly' if plot_title is None else plot_title, xaxis=dict( ticktext=tdvals, tickvals=tdvals, tickangle=90, type='category'), xaxis2=dict( ticktext=tdvals, tickvals=tdvals, tickangle=90, type='category'), yaxis=dict( title='y main' if y_left_label is None else y_left_label ), yaxis2=dict( title='y alt' if y_right_label is None else y_right_label, overlaying='y', side='right') ) fig = go.Figure(data=d_array,layout=layout) if bar_plot: # fix y values, which have all become positive df_yvals = df_in[[c for c in df_in.columns.values if c != x_column]] for i in range(len(df_yvals.columns.values)): fig.data[i].y = df_yvals[df_yvals.columns.values[i]] return fig
def plot_value_array(image, model): predictions1 = classify_image2(image, model)[0] #predictions1 = predictions1.flatten() fig, ax = plt.subplots(figsize=(20, 6), dpi=80) ax.set_xticks(range(43)) ax.bar(range(43), predictions1, color="#777777") plotly_fig = mpl_to_plotly(fig)
def about(request): fig, ax = plt.subplots() ax.plot([1, 3, 4], [3, 2, 5]) plotly_fig = tls.mpl_to_plotly(fig) graph_div = plotly.offline.plot(plotly_fig, auto_open=False, output_type="div") return render(request, 'Trending/about.html', {'fig': graph_div})
def handlePlotly(fig, args): if args['plotly']: import plotly.tools as tls import plotly.offline as py plotly_fig = tls.mpl_to_plotly(fig) py.plot(plotly_fig) else: plt.show()
def q2(pairs): # Measure the degree of each protein with at least 1 interaction in the network (exclude selfinteractions) degs = {} #protein name to deg num neighbors = {} #protein name to list of protein names who are neighbors for p in pairs: #exclude self interactions if (p.proteinA != p.proteinB): #Increment proteinA count in degs if found, otherwise add it if (p.proteinA not in degs): degs[p.proteinA] = 1 tempList = [p.proteinB] neighbors[p.proteinA] = tempList else: degs[p.proteinA] = degs[p.proteinA] + 1 #add proteinB to the list that's already there tempList = neighbors[p.proteinA] tempList.append(p.proteinB) neighbors[p.proteinA] = tempList #Increment proteinB count in degs if found, otherwise add it if (p.proteinB not in degs): degs[p.proteinB] = 1 tempList = [p.proteinA] neighbors[p.proteinB] = tempList else: degs[p.proteinB] = degs[p.proteinB] + 1 #add proteinA to the list that's already there tempList = neighbors[p.proteinB] tempList.append(p.proteinA) neighbors[p.proteinB] = tempList # Plot the degree distribution of the protein-protein interaction network (a histogram is fine) fig = plt.figure() n = list(degs.values()) bins = 75 plt.hist(n, bins) plt.title("Degree distribution of protein-protein interaction network") plt.xlabel("Degree Count") plt.ylabel("Frequency") plotly_fig = tls.mpl_to_plotly(fig) py.plot(plotly_fig, filename='all_probe_data_before_log') #finding highest degree protein max = 0 maxP = "" for k, v in degs.items(): if v > max: max = v maxP = k print("Max degree value ", max) print("Corresponding max protein ", maxP) return degs, neighbors
def show_app_old(self): fig = plt.figure() ax = fig.add_subplot(111) x = [1, 2, 3, 4] y = [10, 20, 25, 30] ax.plot(x, y, color='lightblue', linewidth = 3) ax.scatter(x, y, color='darkgreen', marker ='.') ax.set_xlim(0.5, 4.5) ax.set_facecolor('xkcd:salmon') ax.set_facecolor((1.0, 0.47, 0.42)) plotly_fig = mpl_to_plotly(fig) #graph = dcc.Graph(id='myGraph', fig=plotly_fig) fig = go.Figure( data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])], layout=go.Layout( title=go.layout.Title(text="A Bar Chart") ) ) fig2 = make_subplots(rows=2, cols=1) fig2.add_trace(go.Scatter(y=[4.4, 2, 1], mode="lines", name="scatter 1"), row=1, col=1) fig2.add_trace(go.Scatter(y=[4.1, 2, 1], mode="lines", name="scatter 2"), row=1, col=1) fig2.add_trace(go.Scatter(y=[4, 2.2, 1.5], mode="lines", name="scatter 3", line=dict(color="blue")), row=1, col=1) fig2.add_trace(go.Scatter(y=[4, 2, 1], mode="lines"), row=1, col=1) fig2.add_trace(go.Bar(y=[2, 1, 3]), row=2, col=1) fig2.update_layout(title={'text': "Plot Title", 'y':0.9, 'x':0.5, 'xanchor': 'center','yanchor': 'top'}, xaxis_title="x Axis Title", yaxis_title="y Axis Title",font=dict(family="Courier New, monospace",size=18,color="#7f7f7f"),title_text="A Bar Chart",title_font_size=30) app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='example-graph', figure={ 'data': [ {'x': x, 'y':y}, go.Bar(x=[1, 2, 3], y=[1, 3, 2]) ], 'layout': { 'title': 'Dash Data Visualization' } }, config={'displayModeBar': True, 'scrollZoom': True} ), dcc.Graph(id='myGraph2', figure=fig2, config={'displayModeBar': True, 'scrollZoom': True}), dcc.Graph(id='myGraph', figure=plotly_fig, config={'displayModeBar': True, 'scrollZoom': True}), html.H2(children="Dqwedw") ])
def iplot_mpl( mpl_fig, resize=False, strip_style=False, verbose=False, show_link=True, link_text="Export to plot.ly", validate=True, ): """ Convert a matplotlib figure to a plotly graph and plot inside an IPython notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.plot_mpl`. For more information on converting matplotlib visualizations to plotly graphs call `help(plotly.tools.mpl_to_plotly)` For more information on plotting plotly charts offline in an Ipython notebook call `help(plotly.offline.iplot)` mpl_fig -- a matplotlib.figure to convert to a plotly graph Keyword arguments: resize (default=False) -- allow plotly to choose the figure size. strip_style (default=False) -- allow plotly to choose style options. verbose (default=False) -- print message. show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. Example: ``` from plotly.offline import init_notebook_mode, iplot_mpl import matplotlib.pyplot as plt init_notebook_mode() fig = plt.figure() x = [10, 15, 20, 25, 30] y = [100, 250, 200, 150, 300] plt.plot(x, y, "o") iplot_mpl(fig) ``` """ plotly_plot = tools.mpl_to_plotly(mpl_fig, resize, strip_style, verbose) return iplot(plotly_plot, show_link, link_text, validate)
def transform_analyse_continous(df, var): scatter_plot_figure = plt.figure(figsize=(20, 5)) df = df.copy() plt.scatter(df[var], df[df.columns.values[-1]]) plt.ylabel(df.columns.values[-1]) plt.xlabel(var) plt.show() scatterplot = tls.mpl_to_plotly(scatter_plot_figure) return scatterplot
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) t = NetAssetReport() task = build([t], local_scheduler=True) if task: plotly_fig = tls.mpl_to_plotly(t.fig) div = opy.plot(plotly_fig, auto_open=False, output_type='div') context['graph'] = div return context
def analyse_discrete(df, var): line_plot_figure = plt.figure(figsize=(20, 5)) df[df.columns.values[-1]].plot(label=df.columns.values[-1], legend=False) df[var].plot(secondary_y=True, label=var, legend=True) plt.xticks(rotation=90) plt.show() line_plot = tls.mpl_to_plotly(line_plot_figure) return line_plot
def generar_histograma(numeros_aleatorios): plt.hist(numeros_aleatorios) plt.title("Histograma GCL") plt.xlabel("Valor") plt.ylabel("Frecuencia") fig = plt.gcf() plotly_fig = tls.mpl_to_plotly( fig ) py.plot(plotly_fig, filename='histograma-gcl')
def hist(self, df, column, bins=None, color="b"): m_fig = plt.figure() if bins is not None: df[column].hist(bins=bins, color=color) else: df[column].hist(color=color) p_fig = tools.mpl_to_plotly(m_fig) trace = p_fig["data"][0] self.traces.append(trace)
def show_fig(fig, plotly=False): if plotly: import plotly.tools as tls import plotly.offline as py plotly_fig = tls.mpl_to_plotly(fig) py.plot(plotly_fig) else: import matplotlib.pyplot as plt plt.show()
def plot_quiver_img(self, img, flow, win=0, caption='view'): fig, ax = plt.subplots(1) ax.axis('off') ax.imshow(img.transpose(1, 2, 0)) X, Y, U, V = flow_to_XYUV(flow) ax.quiver(X, Y, U, V, angles='xy', color='y') plotly_fig = mpl_to_plotly(fig) self.vis.plotlyplot(plotly_fig) plt.clf()
def transform_analyse_continous(self): for ind, v in enumerate(self.var): scatter_plot_figure = plt.figure() plt.scatter(self.data[v], self.data[self.data_to_search.values[0]]) plt.ylabel(self.data_to_search.values[0]) plt.xlabel(v) plt.show() scatterplot = tls.mpl_to_plotly(scatter_plot_figure) return scatterplot
def plot(self, mpl=False): # Generates matplotlib obj mpl_fig, ax = plt.subplots() ax.set_ylabel("Absorbance " + self.params.wavelength) ax.set_xlabel("Groups") self.df.boxplot(ax=ax) #labels = [item.get_text() for item in ax.get_xticklabels()] if mpl: #return mpl_fig return None else: return plot(tls.mpl_to_plotly(mpl_fig))
def test_pandas_time_series_date_formatter(self): ndays = 3 x = pd.date_range('1/1/2001', periods=ndays, freq='D') y = [random.randint(0, 10) for i in range(ndays)] s = pd.DataFrame(y, columns=['a']) s['Date'] = x s.plot(x='Date') fig = plt.gcf() pfig = tls.mpl_to_plotly(fig) expected_x = ['2001-01-01 00:00:00', '2001-01-02 00:00:00', '2001-01-03 00:00:00'] expected_x0 = 11323.0 # this is floating point days since epoch x0 = fig.axes[0].lines[0].get_xydata()[0][0] self.assertEqual(x0, expected_x0) self.assertEqual(pfig['data'][0]['x'], expected_x)
def mpl_to_json(figure, resize = True, strip_style = False): """ Turn the matplotlib figure object into a JSON data object using tools provided by plotly.py Positional Arguments: fig -- a figure object from matplotlib Keywords Arguments: resize (default is True) -- allow the plotly backend to choose the size strip_style (default is False) -- allow plotly to choose style options """ fig = tools.mpl_to_plotly(figure, resize=resize, strip_style=strip_style) # get the json scheme data = json.dumps(fig['data'] if 'data' in fig else [], cls=utils.PlotlyJSONEncoder) layout = json.dumps(fig['layout'] if 'layout' in fig else [], cls=utils.PlotlyJSONEncoder) # make the total json object return str(fig)
def quiver_region(self,fname='test'): plotly_fig = tls.mpl_to_plotly(fig) x = self.x y = self.y z = self.z # Set up a regular grid of interpolation points xi, yi = np.linspace(min(x), max(x), intervals), np.linspace(min(y), max(y), intervals) xi, yi = np.meshgrid(xi, yi) # Interpolate rbf = scipy.interpolate.Rbf(x, y, z, function='linear') zi = rbf(xi, yi) quiver = tls.TraceFactory.create_quiver() data = Data([quiver]) plotly_fig = Figure(data=data) unique_url = py.plot(plotly_fig, filename = self.name) msg =("Plotly Plot saved to " + unique_url) plt.close() return msg
def plot(self, mpl=True, plot_type="box", **plt_kwargs): """ Parameters ---------- mpl : boolean, optional Set to True to render a matplotlib plot, otherwise a Plotly plot is rendered plot_type : {"box", "bar", "line", "hist"}, optional Type of plot to render \**plot_kwargs : dict, optional Optional dictionary of specifications for your plot type of choice """ mpl_fig, ax = plt.subplots() nl = "\n" if mpl else "<br>" ax.set_ylabel(self.op_type + nl + self.params["wavelength"]) self.df.plot(kind=plot_type, ax=ax) labels = [item.label.get_text() for item in ax.xaxis.get_major_ticks()] if mpl: return None else: if not plt_kwargs: plt_kwargs = { "layout": { "xaxis": { "tickmode": "array", "ticktext": labels, "tickvals": list(range(1, len(labels)+1)), "tickangle": 0, "tickfont": { "size": 10 }, } } } pyfig = tls.mpl_to_plotly(mpl_fig) pyfig.update(plt_kwargs) return py.iplot(pyfig)
def plot_mpl(fig, resize=True, strip_style=False, update=None, **plot_options): """Replot a matplotlib figure with plotly. This function: 1. converts the mpl figure into JSON (run help(plolty.tools.mpl_to_plotly)) 2. makes a request to Plotly to save this figure in your account 3. opens your figure in a browser tab OR returns the unique figure url Positional agruments: fig -- a figure object from matplotlib Keyword arguments: resize (default=True) -- allow plotly to choose the figure size strip_style (default=False) -- allow plotly to choose style options update (default=None) -- update the resulting figure with an 'update' dictionary-like object resembling a plotly 'Figure' object Additional keyword arguments: plot_options -- run help(plotly.plotly.plot) """ fig = tools.mpl_to_plotly(fig, resize=resize, strip_style=strip_style) if update and isinstance(update, dict): try: fig.update(update) fig.validate() except exceptions.PlotlyGraphObjectError as err: err.add_note("Your updated figure could not be properly validated.") err.prepare() raise elif update is not None: raise exceptions.PlotlyGraphObjectError( "'update' must be dictionary-like and a valid plotly Figure " "object. Run 'help(plotly.graph_objs.Figure)' for more info." ) return plot(fig, **plot_options)
plt.xlabel('Time(s)') plt.ylabel('RAD (units)') print '###########' print 'saving fig for ' + readfile[i][0] + ' this is the #' + str(numsave) + ' time' plt.savefig(readfile[i][0] + 'ZONE_' + str(k + 1) + '.png', dpi=200) numsave += 1 plt.close() print 'plot creation complete' axt.set_title('Zone # ' + str(k + 1) + ' Estimated integration time: ' + str(len(goodtime)*10 + len(badtime)*10) + '(s)') #axt.errorbar(goodtime, goodflux, yerr=gooderr, fmt='o') #axt.errorbar(badtime, badflux, yerr=baderr, # fmt='ro') # Work on getting flags running, your close but not there axt.plot(gAppOutput[k], fluxfile[k], 'ko-') axt.plot(goodtime, goodflux, 'ko') axt.plot(badtime, badflux, 'ro') plotly_fig = tls.mpl_to_plotly(fig) plotly_fig["data"][0]["error_y"].update({ "visible": True, "color":"rgb(255,127,14)", "array":fluxfile[k] }) url = py.plot_mpl(fig, filename = readfile[i][0] + '_ZONE_' + str(k+1), auto_open = False) urlout.append(readfile[i][0] + '_ZONE_' + str(k+1) + '\t' + url + '\n') currentdir = os.path.abspath('.') os.chdir(start) try: logfile = open('HTMLOUT.log', 'a') except IOError: logfile = open('HTMLOUT.log', 'w') logfile.write(readfile[i][0] + '\t' + str(k+1) + '\n') logfile.close()
def plot_mpl(mpl_fig, resize=False, strip_style=False, verbose=False, show_link=True, link_text='Export to plot.ly', validate=True, output_type='file', include_plotlyjs=True, filename='temp-plot.html', auto_open=True): """ Convert a matplotlib figure to a Plotly graph stored locally as HTML. For more information on converting matplotlib visualizations to plotly graphs, call help(plotly.tools.mpl_to_plotly) For more information on creating plotly charts locally as an HTML document or string, call help(plotly.offline.plot) mpl_fig -- a matplotlib figure object to convert to a plotly graph Keyword arguments: resize (default=False) -- allow plotly to choose the figure size. strip_style (default=False) -- allow plotly to choose style options. verbose (default=False) -- print message. show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. output_type ('file' | 'div' - default 'file') -- if 'file', then the graph is saved as a standalone HTML file and `plot` returns None. If 'div', then `plot` returns a string that just contains the HTML <div> that contains the graph and the script to generate the graph. Use 'file' if you want to save and view a single graph at a time in a standalone HTML file. Use 'div' if you are embedding these graphs in an HTML file with other graphs or HTML markup, like a HTML report or an website. include_plotlyjs (default=True) -- If True, include the plotly.js source code in the output file or string. Set as False if your HTML file already contains a copy of the plotly.js library. filename (default='temp-plot.html') -- The local filename to save the outputted chart to. If the filename already exists, it will be overwritten. This argument only applies if `output_type` is 'file'. auto_open (default=True) -- If True, open the saved file in a web browser after saving. This argument only applies if `output_type` is 'file'. Example: ``` from plotly.offline import init_notebook_mode, plot_mpl import matplotlib.pyplot as plt init_notebook_mode() fig = plt.figure() x = [10, 15, 20, 25, 30] y = [100, 250, 200, 150, 300] plt.plot(x, y, "o") plot_mpl(fig) ``` """ plotly_plot = tools.mpl_to_plotly(mpl_fig, resize, strip_style, verbose) return plot(plotly_plot, show_link, link_text, validate, output_type, include_plotlyjs, filename, auto_open)
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
print rmax10s print vel10s bin_means, bin_edges, binnumber = scipy.stats.binned_statistic(rmax10s, vel10s, statistic='mean', bins=4) #print bin_means #print bin_edges plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5, label='binned statistic of data') #digitizedrmax10s = np.digitize(rmax10s, bins) #print digitizedrmax10s #bin_meansrmax10s = [rmax10s[digitizedrmax10s == i].mean() for i in range(1, len(bins))] #print bin_meansrmax10s #digitizedvel10s = np.digitize(vel10s, bins) #bin_meansvel10s = [vel10s[digitizedvel10s == i].mean() for i in range(1, len(bins))] #plt.loglog(digitizedrmax10s, digitizedvel10s, '-', alpha=0.08, label='mean 10th percentile') plt.loglog(rmax10s, vel10s, 'o', alpha=0.08, label='10th-50th host mass percentile') plt.loglog(rmax50s, vel50s, 'o', alpha=0.08, label='50th-90th host mass percentile') plt.loglog(rmax90s, vel90s, 'o', alpha=0.08, label='>=90th host mass percentile') plt.loglog(rmaxxs, velxs, 'o', alpha=0.08, label='<10th host mass percentile') plt.xlim(xmin=0.38, xmax=50) plt.ylim(ymin=10.0, ymax=200) plt.xlabel('Rmax (kpc)') plt.ylabel('Vmax (km/s)') plt.title('Rmax-Vmax by Host Mass') #spearman = scipy.stats.spearmanr(rmaxs, vmaxs) #print spearman plot_mpl_fig() mpl_fig1 = plt.gcf() py_fig1 = tls.mpl_to_plotly(mpl_fig1, verbose=True) py.iplot_mpl(mpl_fig1, strip_style=True, filename='Rmax-Vmax Percentile') py_fig1_ss = tls.mpl_to_plotly(mpl_fig1, strip_style=True) py.plot(py_fig1_ss, filename='Rmax-Vmax Percentile')
def plot_2d_graph(self, data_frame, gp, type): matplotlib.rcdefaults() # set the matplotlib style sheet plt.style.use(Constants().plotfactory_pythalesians_style_sheet[Constants().plotfactory_default_stylesheet]) if hasattr(gp, 'style_sheet'): plt.style.use(Constants().plotfactory_pythalesians_style_sheet[gp.style_sheet]) scale_factor = Constants().plotfactory_scale_factor if hasattr(gp, 'scale_factor'): scale_factor = gp.scale_factor dpi = Constants().plotfactory_dpi if hasattr(gp, 'dpi'): dpi = gp.dpi width = Constants().plotfactory_width; height = Constants().plotfactory_height if hasattr(gp, 'width'): width = gp.width if hasattr(gp, 'height'): width = gp.height fig = plt.figure(figsize = ((width * scale_factor)/dpi, (height * scale_factor)/dpi), dpi = dpi) # add a subplot ax = fig.add_subplot(111) matplotlib.rcParams.update({'font.size': matplotlib.rcParams['font.size'] * scale_factor}) # format Y axis y_formatter = matplotlib.ticker.ScalarFormatter(useOffset = False) ax.yaxis.set_major_formatter(y_formatter) y_axis_2_series = [] ax2 = [] color_2_series = [] linewidth_2_series = [] if hasattr(gp, 'resample'): data_frame = data_frame.asfreq(gp.resample) # create a second y axis if necessary if hasattr(gp, 'y_axis_2_series'): if gp.y_axis_2_series == []: pass else: y_axis_2_series = gp.y_axis_2_series ax2 = ax.twinx() # matplotlib.rcParams.update({'figure.subplot.right': matplotlib.rcParams['figure.subplot.right'] - 0.05}) # do not use a grid with multiple y axes ax.yaxis.grid(False) ax2.yaxis.grid(False) # is there a second palette? if hasattr(gp, 'color_2_series'): if hasattr(gp.color_2_series, 'values'): color_2_series = [str(x) for x in gp.color_2_series.values] else: color_2_series = [str(x) for x in gp.color_2_series] # is there a second linewidth series if hasattr(gp, 'linewidth_2_series'): if hasattr(gp.linewidth_2_series, 'values'): linewidth_2_series = [str(x) for x in gp.linewidth_2_series.values] else: linewidth_2_series = [str(x) for x in gp.linewidth_2_series] # plot the lines (using custom palettes as appropriate) try: color = []; color_2 = [] linewidth_2 = matplotlib.rcParams['axes.linewidth'] exclude_from_color = [] if hasattr(gp, 'color'): if isinstance(gp.color, list): color = gp.color else: try: color = self.create_colormap( len(data_frame.columns.values) - len(color_2_series), gp.color) except: pass if hasattr(gp, 'width'): if isinstance(gp.width, list): color = gp.color else: try: color = self.create_colormap( len(data_frame.columns.values) - len(color_2_series), gp.color) except: pass if hasattr(gp, 'color_2'): if isinstance(gp.color_2, list): color_2 = gp.color_2 else: try: color_2 = self.create_colormap(len(color_2_series), gp.color_2) except: pass if hasattr(gp, 'exclude_from_color'): if not(isinstance(gp.exclude_from_color, list)): gp.exclude_from_color = [gp.exclude_from_color] exclude_from_color = [str(x) for x in gp.exclude_from_color] if hasattr(gp, 'linewidth_2'): linewidth_2 = gp.linewidth_2 axis_1_color_index = 0 axis_2_color_index = 0 if type == 'bar': # bottom = np.cumsum(np.vstack((np.zeros(data_frame.values.shape[1]), data_frame.values)), axis=0)[:-1] # bottom = np.vstack((np.zeros((data_frame.values.shape[1],), dtype=data_frame.dtype), # np.cumsum(data_frame.values, axis=0)[:-1])) yoff = np.zeros(len(data_frame.index.values)) # the bottom values for stacked bar chart # some lines we should exclude from the color and use the default palette for i in range(0, len(data_frame.columns.values)): label = str(data_frame.columns[i]) ax_temp = self.get_axis(ax, ax2, label, y_axis_2_series) color_spec, axis_1_color_index, axis_2_color_index = \ self.get_color(label, axis_1_color_index, axis_2_color_index, color, color_2, exclude_from_color, color_2_series) xd = data_frame.index; yd = data_frame.ix[:,i] if (type == 'line'): linewidth = self.get_linewidth(label, linewidth_2, linewidth_2_series) ax_temp.plot(xd, yd, label = label, color = color_spec, linewidth = linewidth) elif(type == 'bar'): ax_temp.bar(xd, yd, label = label, color = color_spec, bottom = yoff) yoff = yoff + yd elif(type == 'scatter'): ax_temp.scatter(xd, yd, label = label, color = color_spec) if hasattr(gp, 'line_of_best_fit'): if gp.line_of_best_fit == True: self.trendline(ax_temp, xd.values, yd.values, order=1, color= color_spec, alpha=1, scale_factor = scale_factor) except: pass # format X axis self.format_x_axis(ax, data_frame, gp) try: fig.suptitle(gp.title, fontsize = 14 * scale_factor) except: pass try: source = Constants().plotfactory_source source_color = 'black' display_brand_label = False if hasattr(gp, 'source'): source = gp.source display_brand_label = True if hasattr(gp, 'source_color'): source_color = self.get_color_code(gp.source_color) if display_brand_label or Constants().plotfactory_display_brand_label: ax.annotate('Source: ' + source, xy = (1, 0), xycoords='axes fraction', fontsize=7 * scale_factor, xytext=(-5 * scale_factor, 10 * scale_factor), textcoords='offset points', ha='right', va='top', color = source_color) except: pass if hasattr(gp, 'display_brand_label'): if gp.display_brand_label is True: self.create_brand_label(ax, anno = Constants().plotfactory_brand_label, scale_factor = scale_factor) else: if Constants().plotfactory_display_brand_label is True: self.create_brand_label(ax, anno = Constants().plotfactory_brand_label, scale_factor = 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 * scale_factor}) leg.get_frame().set_linewidth(0.0) leg.get_frame().set_alpha(0) if ax2 is not []: leg2 = ax2.legend(loc = 1, prop={'size':10 * scale_factor}) leg2.get_frame().set_linewidth(0.0) leg2.get_frame().set_alpha(0) except: pass try: if gp.display_legend == False: if leg is not[]: leg.remove() if leg2 is not[]: leg.remove() except: pass try: plt.savefig(gp.file_output, transparent=False) except: pass try: if hasattr(gp, 'silent_display'): if gp.silent_display is False: plt.show() else: plt.show() except: pass # convert to D3 format with mpld3 try: if hasattr(gp, 'html_file_output'): mpld3.save_d3_html(fig, gp.html_file_output) if hasattr(gp, 'display_mpld3'): if gp.display_mpld3 == True: mpld3.show(fig) except: pass # convert to Plotly format (fragile!) # TODO better to create Plotly graphs from scratch rather than convert from matplotlib # TODO also dependent on matplotlib version for support try: if hasattr(gp, 'plotly_url'): plotly.tools.set_credentials_file(username = Constants().plotly_username, api_key = Constants().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
def mpl_to_plotly(figure, resize = True, strip_style = False): """ wrapper function for plotly.tools.mpl_to_plotly """ return tools.mpl_to_plotly(figure, resize=resize, strip_style=strip_style)
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) # 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) # 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) if type == "bar": # bottom = np.cumsum(np.vstack((np.zeros(data_frame.values.shape[1]), data_frame.values)), axis=0)[:-1] # bottom = np.vstack((np.zeros((data_frame.values.shape[1],), dtype=data_frame.dtype), # np.cumsum(data_frame.values, axis=0)[:-1])) yoff = np.zeros(len(data_frame.index.values)) # the bottom values for stacked bar chart # 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.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) xd = data_frame.index 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": ax_temp.bar(xd, yd, label=label, color=color_spec[i], bottom=yoff) yoff = yoff + yd 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, ) except: pass # format X axis self.format_x_axis(ax, data_frame, gp) 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
# In[25]: py.iplot_mpl(mpl_fig, filename='baltimore-poverty') # So, at the moment, matplotlib legends do not fully convert to plotly legends (please refer to our [user guide](https://plot.ly/python/matplotlib-to-plotly-tutorial/#Careful,-matplotlib-is-not-perfect-%28yet%29)). Let's tweak this now. # In[26]: import plotly.tools as tls # In[27]: # Convert mpl fig object to plotly fig object, resize to plotly's default. py_fig = tls.mpl_to_plotly(mpl_fig, resize=True) # In[28]: # Give each trace a name to appear in legend. py_fig['data'][0]['name'] = py_fig['layout']['annotations'][0]['text'] py_fig['data'][1]['name'] = py_fig['layout']['annotations'][1]['text'] # In[29]: # Delete misplaced legend annotations. py_fig['layout'].pop('annotations', None)
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
def iplot_mpl(mpl_fig, resize=False, strip_style=False, verbose=False, show_link=True, link_text='Export to plot.ly', validate=True, image=None, image_filename='plot_image', image_height=600, image_width=800): """ Convert a matplotlib figure to a plotly graph and plot inside an IPython notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.plot_mpl`. For more information on converting matplotlib visualizations to plotly graphs call `help(plotly.tools.mpl_to_plotly)` For more information on plotting plotly charts offline in an Ipython notebook call `help(plotly.offline.iplot)` mpl_fig -- a matplotlib.figure to convert to a plotly graph Keyword arguments: resize (default=False) -- allow plotly to choose the figure size. strip_style (default=False) -- allow plotly to choose style options. verbose (default=False) -- print message. show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets the format of the image to be downloaded, if we choose to download an image. This parameter has a default value of None indicating that no image should be downloaded. image_filename (default='plot_image') -- Sets the name of the file your image will be saved to. The extension should not be included. image_height (default=600) -- Specifies the height of the image in `px`. image_width (default=800) -- Specifies the width of the image in `px`. Example: ``` from plotly.offline import init_notebook_mode, iplot_mpl import matplotlib.pyplot as plt fig = plt.figure() x = [10, 15, 20, 25, 30] y = [100, 250, 200, 150, 300] plt.plot(x, y, "o") init_notebook_mode() iplot_mpl(fig) # and if you want to download an image of the figure as well iplot_mpl(fig, image='jpeg') ``` """ plotly_plot = tools.mpl_to_plotly(mpl_fig, resize, strip_style, verbose) return iplot(plotly_plot, show_link, link_text, validate, image=image, filename=image_filename, image_height=image_height, image_width=image_width)
def mu2e_plot(df, x, y, conditions=None, mode='mpl', info=None, savename=None, ax=None, auto_open=True): """Generate 2D plots, x vs y. Generate a 2D plot for a given DF and two columns. An optional selection string is applied to the data via the :func:`pandas.DataFrame.query` interface, and is added to the title. This function supports matplotlib and various plotly plotting modes. Args: df (pandas.DataFrame): The input DF, must contain columns with labels corresponding to the 'x' and 'y' args. x (str): Name of the independent variable. y (str): Name of the dependent variable. conditions (str, optional): A string adhering to the :mod:`numexpr` syntax used in :func:`pandas.DataFrame.query`. mode (str, optional): A string indicating which plotting package and method should be used. Default is 'mpl'. Valid values: ['mpl', 'plotly', 'plotly_html', 'plotly_nb'] info (str, optional): Extra information to add to the legend. savename (str, optional): If not `None`, the plot will be saved to the indicated path and file name. ax (matplotlib.axis, optional): Use existing mpl axis object. auto_open (bool, optional): If `True`, automatically open a plotly html file. Returns: axis object if 'mpl', else `None`. """ _modes = ['mpl', 'plotly', 'plotly_html', 'plotly_nb'] if mode not in _modes: raise ValueError(mode+' not one of: '+', '.join(_modes)) if conditions: df, conditions_title = conditions_parser(df, conditions) leg_label = y+' '+info if info else y ax = df.plot(x, y, ax=ax, kind='line', label=leg_label, legend=True, linewidth=2) ax.grid(True) plt.ylabel(y) plt.title(' '.join([x for x in [x, 'v', y, conditions] if x])) if 'plotly' in mode: fig = ax.get_figure() py_fig = tls.mpl_to_plotly(fig) py_fig['layout']['showlegend'] = True if mode == 'plotly_nb': # init_notebook_mode() iplot(py_fig) elif mode == 'plotly_html': if savename: plot(py_fig, filename=savename, auto_open=auto_open) else: plot(py_fig, auto_open=auto_open) elif savename: plt.savefig(savename) if mode == 'mpl': return ax else: return None