def save_figure(fn, fig): plotly.offline.plot(fig, filename=fn + '.html', auto_open=False, show_link=True) pio.write_image(fig, fn + '.png') pio.write_image(fig, fn + '.pdf')
def plot_scatter_dynamicTraces(datasets, datasets_labels, datsets_colors, title): traces = [] for x in xrange(0, len(datasets)): traces.append( go.Scatter(x=datasets[x]['path_lenght_total_meters'], y=datasets[x]['computation_time_millis'], mode='markers', marker=go.Marker(color=datsets_colors[x]), name=datasets_labels[x])) layout = go.Layout( title=title, xaxis=dict(title='Distance between points (in meters)', titlefont=dict(family='Courier New, monospace', size=18, color='#7f7f7f')), yaxis=dict(title='Computation time (seconds)', titlefont=dict(family='Courier New, monospace', size=18, color='#7f7f7f'))) fig = dict(data=traces, layout=layout) plotly.offline.iplot(fig, filename='./scatter_time_vs_pathLength', image='png') pio.write_image(fig, '/home/mfaria/Downloads/plot_scatter_dynamicTraces.svg', scale=2)
def plot_bubble_area_hist(df, bSave=False, dirname=None): """Plots a histogram of the area of the bubbles """ import plotly import plotly.graph_objs as go import plotly.io as pio data = [] for i in range(len(df['Frame'].unique())): data.append( go.Histogram(x=df[df['Frame'] == df['Frame'].unique()[i]]['Area'], name=df['Frame'].unique()[i])) fig = go.Figure({ "data": data, "layout": go.Layout(width=800, height=500, xaxis=dict(title='Area (mm2)', linecolor='black', linewidth=2, mirror=True), showlegend=True) }) plotly.offline.plot(fig, auto_open=True) if bSave: pio.write_image(fig, dirname + '/' + 'BubbleHist.pdf')
def printTable(data, outputPath): headerColor, rowOddColor, rowEvenColor = '#CCE5FF', '#CCF3FF', 'white' cellsData = {'values': [], 'align': ['left', 'center'], 'height': 30} for i in range(len(data['header'])): cellsData['values'].append([]) for i in range(len(data['values'])): for j in range(len(data['header'])): cellsData['values'][j].append(data['values'][i][j]) colors = [headerColor] + [ rowOddColor if i % 2 else rowEvenColor for i in range(len(data['header']) - 1) ] cellsData['fill'] = {'color': colors} trace = go.Table(header={'values' : data['header'], 'fill': {'color':headerColor}}, cells=cellsData, \ columnwidth=[250, 180]) layout = dict(width=1800, height=1000, font=dict(family='"Open Sans", verdana, arial, sans-serif', size=18, color='#444')) fig = dict(data=[trace], layout=layout) plot(fig, filename=os.path.join(outputPath, HTML_OUTPUT_NAME)) pio.write_image(fig, os.path.join(outputPath, PNG_OUTPUT_NAME))
def plot_evolution_with_dimension(length_1, lenght_2, distance_for_cdist, nb_try, min_dim, max_dim, name_fig): evol_dist = [] for dim in range(min_dim, max_dim): evol_dist.append( random_dtw(dim, length_1, lenght_2, distance_for_cdist, nb_try)) print(evol_dist) layout = go.Layout( title=go.layout.Title(text='Evol', font=dict(family='Times'), xref='paper', x=0), xaxis=go.layout.XAxis(title=go.layout.xaxis.Title( text='dimension', font=dict(family='Times', size=18, color='#7f7f7f'))), yaxis=go.layout.YAxis(title=go.layout.yaxis.Title( text='random distance', font=dict(family='Times', size=18, color='#7f7f7f')), )) fig = go.Figure(layout=layout) # you plot the correlation btwn x and y fig.add_scatter(x=list(range(min_dim, max_dim)), y=evol_dist, mode='lines', name='fitted line', showlegend=False) # save the figure pio.write_image(fig, name_fig + '.pdf')
def save_static(self): try: pio.write_image(self.fig, self.path.replace('html', 'png')) except ValueError as e: logging.warning("Nanoplotter: orca not found, not creating static image of html. " "See https://github.com/plotly/orca") logging.warning(e, exc_info=True)
def make_chart(self, file_name='chart.png'): data = dict( type='sankey', node = dict( pad = 15, thickness = 20, line = dict( color = "black", width = 0.5 ), label = ["A1", "A2", "B1", "B2", "C1", "C2"], color = ["blue", "blue", "blue", "blue", "blue", "blue"] ), link = dict( source = [0,1,0,2,3,3], target = [2,3,3,4,4,5], value = [8,4,2,8,4,2] )) layout = dict( title = "Basic Sankey Diagram", font = dict( size = 10 ) ) fig = dict(data=[data], layout=layout) pio.write_image(fig, file_name)
def print_report(self, directory, plot_format='pdf'): for plot_id in self._plots: name = "_".join(plot_id) for plot in self._plots[plot_id]: figure = plot.figure pio.write_image( figure, os.path.join(directory, name + "." + plot_format))
def generate_candle_image_from_db_by_weeks(share_item, start_date, weeks=52, output_folder=''): ''' Generates candle image using data from the database ''' data = [] for monday, friday in generate_week_dates(start_date, weeks): week_data = list(ShareDataItem.objects.filter(share=share_item).filter(date__range=[monday, friday]).order_by('-date')) if week_data: summary = {} summary['open_price'] = week_data[-1].open_price summary['close_price'] = week_data[0].close_price summary['high_price'] = max(week_data, key=lambda item: item.high_price).high_price summary['low_price'] = min(week_data, key= lambda item: item.low_price).low_price summary['date'] = friday data.append(summary) df = pd.DataFrame(data) trace = go.Candlestick( x=df.date, open=df.open_price, high=df.high_price, low=df.low_price, close=df.close_price ) layout = go.Layout(xaxis=dict(rangeslider=dict(visible=False))) fig = go.Figure(data=[trace], layout=layout) fig.layout.template = 'plotly_white' base_name = share_item.ticker + '.png' image_path = output_folder + '/' + base_name pio.write_image(fig, image_path, width=500, height=335) print('Successfully created image ' + image_path)
def id_3(data): aux = 0 dado = [] z = 0 for i in data["data"]: df = pd.DataFrame.from_dict(i) eixo_x = str(df.columns[0]) eixo_y = str(df.columns[1]) trace = go.Scatter(x=df.loc[:, eixo_x], y=df.loc[:, eixo_y], mode='lines+markers+text', text=df.loc[:, eixo_y], textposition='bottom center', name=data['names'][z]) dado.append(trace) z = z + 1 layout = go.Layout(title=data['title']) figure = go.Figure(data=dado, layout=layout) pio.write_image(figure, 'images/fig.png')
def plot_evolution_with_len(length_min, lenght_max, distance_for_cdist, nb_try, dim, name_fig): evol_dist = [] for leng in range(length_min, lenght_max): evol_dist.append( random_dtw(dim, leng, leng, distance_for_cdist, nb_try)) #evol_dist = [0.9244184515300428, 1.3507927079775819, 1.8953683994705877, 2.4164033165307894, 3.078017969791574, 3.5451338898270066, 3.8834481672845627, 4.419339504421014, 4.929312150282599, 5.295734833813404, 5.677188914851658, 6.3604791638624345, 6.401814264195343, 7.04105355729374, 7.677628549582872, 8.167956434624223, 8.69908235446326, 8.995387920683337, 9.174546910183219, 10.08512368328054, 10.451475420024673, 10.636857194244064, 11.393734396557317, 11.98788877714612, 11.99260450811431, 12.777608772282964, 12.778001918199413, 13.423174160537071, 13.780544588074179, 14.392920760371453, 14.96848321383208, 15.46319106461876, 16.22948537989721, 16.425017514508678, 16.878242066406663, 17.17548436842818, 17.7774467130331, 18.20496954585564, 18.3381123333226, 19.255758106963853, 19.84398311128651, 19.84627547720434, 20.571929630668553, 20.910664435519838, 21.487493599042047, 21.78891178691278, 22.210448540716584, 23.359410022663074, 23.00198941136967, 23.390665909858498, 24.02559960143591, 24.867349020481875, 24.88244134695304, 25.98445817885347, 25.883857617614797, 26.406262437726692, 27.363585641640036, 27.62783716052433, 27.65636942183851, 28.36497986903198, 28.916510784921552, 29.13178885907545, 30.03558322310999, 30.024455252759488, 30.642342470720575, 30.87941129481068, 31.695468603126137, 31.555577077386122, 32.147240484857534, 33.14356474543625, 33.4930579623546, 33.845940385257016, 34.4251507329126, 34.6541119223024, 35.13020073716517, 35.435646100605105, 36.02059806027671, 35.878206059824414, 36.86396012833017, 37.139630699988516, 37.3972232842984, 38.064723046402975, 38.53765721451534, 39.238206941313805, 39.693134424957485, 39.85683533797666, 39.893693308593406, 40.99388383417763, 41.40841115956261, 41.80706268864515, 42.71695395325237, 42.36003200993532, 43.57041069241617, 43.72312624494503, 44.69736247639636, 44.3356386196287, 45.10948612403638, 45.87740286605979, 46.65415117978885, 46.42349349750527, 46.96884013373549, 46.986471459677155, 47.52170575028901, 48.63862899894237, 48.85977743480101, 49.42741050967709, 49.342940471237974, 49.71675807954058, 50.521044498722546, 51.41492390536246, 50.94726062485392, 51.764335272511666, 52.167366927752816, 52.481607295842885, 53.17333474877533, 53.4459672975531, 53.3550557453019, 54.92344608482172, 55.119760391444395, 55.12788907631439, 56.23660645259143, 56.95121330374064, 56.656807256110596, 56.963609698749856, 57.74024863755208, 58.581524222094906, 58.89197602684423, 59.102798593629046, 59.6928693318405, 60.24153671106531, 60.453148503910725, 61.1788992255016, 61.44209093999771, 61.664544443794355, 61.87036410811632, 62.63445407877545, 63.66630810846576, 63.79297960904965, 64.02874725539911, 65.05092869335913, 65.48925129176443, 65.28811453398272, 66.42282525343099, 66.60478814902703, 66.8905539933685, 67.44827964742701, 68.3705186658108, 67.95891234840168, 68.38101822826553, 68.91923283829, 69.29291644966138, 70.18665647244956, 69.91892372840867, 71.67342463090085, 71.40155550341318, 71.37516822196531, 71.89652606969257, 72.77351215753846, 72.38440462804617, 73.48218216041623, 74.57367645793732, 74.40755938022447, 75.61079871652382, 75.85369864185125, 75.91256417476934, 76.53561566996765, 77.08702184858045, 77.32665757110153, 78.16365920812619, 78.07940240422725, 78.89869906584177, 79.06192474679548, 79.89111660521982, 80.03806939455772, 80.40198602423798, 81.12453313119207, 81.08450539657146, 81.87680654261554, 82.16043702976306, 83.04337513323824, 82.91431388724827, 83.7666027701332, 83.58246288994455, 85.10454035814158, 85.22545986451196, 85.80602193488214, 85.80543781933584, 86.45845772078516, 86.66503187772597, 87.35958349187968, 87.21248332860984, 88.2721550004548, 88.52823547130133, 89.06569201993662, 89.28519705802732, 90.1514118047247, 90.75702366611661, 90.84336486934026] print(evol_dist) layout = go.Layout( title=go.layout.Title(text='Evol', font=dict(family='Times'), xref='paper', x=0), xaxis=go.layout.XAxis(title=go.layout.xaxis.Title( text='lenght x and y', font=dict(family='Times', size=18, color='#7f7f7f'))), yaxis=go.layout.YAxis(title=go.layout.yaxis.Title( text='random distance', font=dict(family='Times', size=18, color='#7f7f7f')), )) fig = go.Figure(layout=layout) # you plot the correlation btwn x and y fig.add_scatter(x=list(range(length_min, lenght_max)), y=evol_dist, mode='lines', name='fitted line', showlegend=False) # save the figure pio.write_image(fig, name_fig + '.pdf')
def create_graph(freq): # Add credentials... f**k plotly init_ploty() months = [f[0] for f in freq] data = [f[1] for f in freq] # Create and style traces line = go.Scatter(x=months, y=data, name='Dream frequency by month', line=dict(color=('rgb(205, 12, 24)'), width=4)) data = [line] # Edit the layout layout = dict( title='Number of dreams per month', xaxis=dict(title='Month'), yaxis=dict(title='Number of dreams'), autosize=False, width=2000, height=700, ) fig = dict(data=data, layout=layout) pio.write_image(fig, 'frequency.png') print('run "open frequency.png" to see the graph!')
def plot_output(outfile_name): """ Plot the output dataset using Plotly. Linear regression line is calculated Scipy linregress function. Args: outfile_name: Returns: """ df = pd.read_csv(os.path.join('output_dataset/', outfile_name)) x = df['Unemployment rate(%)'] y = df['Death rate(deaths/1000 population)'] # Generated linear fit slope, intercept, r_value, p_value, std_err = stats.linregress(x, y) line = slope * x + intercept p1 = go.Scatter(x=x, y=y, mode='markers', name='Value') p2 = go.Scatter(x=x, y=line, mode='lines', name='Fit') layout = go.Layout( title='Death Rates per Country in relation to Pop. Unemployment %', xaxis={'title': x.name}, yaxis={'title': y.name}, ) fig = dict(data=[p1, p2], layout=layout) pio.write_image(fig, f'output_dataset/{outfile_name}.png')
def plot_flight_network(df, base_dir, subset): dfC = df.set_index('FL_DATE') dfJuly = dfC.loc['2018-07', :].reset_index() dfRoutes = (dfJuly.groupby(['ORIGIN', 'DEST']).agg({ 'FL_DATE': 'count' }).rename(columns={ 'FL_DATE': 'ct' }).reset_index()) dfPosO = (dfJuly.groupby('ORIGIN').agg({ 'ORIGIN_LAT': 'mean', 'ORIGIN_LONG': 'mean' }).reset_index()) dfPosD = (dfJuly.groupby('DEST').agg({ 'DEST_LAT': 'mean', 'DEST_LONG': 'mean' }).reset_index()) newRoutes = dfRoutes.merge(dfPosO, on='ORIGIN', how='left').merge(dfPosD, on='DEST', how='left') fig = go.Figure() fig.add_trace( go.Scattergeo(locationmode='USA-states', lon=dfPosO['ORIGIN_LONG'], lat=dfPosO['ORIGIN_LAT'], mode='markers', marker=dict(size=2, color='rgb(255, 0, 0)', line=dict(width=3, color='rgba(68, 68, 68, 0)')))) for i in range(len(newRoutes)): fig.add_trace( go.Scattergeo( locationmode='USA-states', lon=[newRoutes['ORIGIN_LONG'][i], newRoutes['DEST_LONG'][i]], lat=[newRoutes['ORIGIN_LAT'][i], newRoutes['DEST_LAT'][i]], mode='lines', line=dict(width=1, color='rgb(252, 32, 128)'), opacity=float(newRoutes['ct'][i] / newRoutes['ct'].max()))) fig.update_layout( title_text='July 2018 Flight Paths<br>(Hover for airport names)', showlegend=False, geo=dict( scope='north america', projection_type='azimuthal equal area', showland=True, landcolor='rgb(0, 0, 0)', countrycolor='rgb(100, 100, 100)', ), ) path = os.path.join(base_dir, 'network.png') fig.show() pio.write_image(fig, path, format='png')
def write_graph_image(self): basic_path = self.write_path if not os.path.exists(os.path.join(basic_path, 'graph_images')): os.mkdir(os.path.join(basic_path, 'graph_images')) for i, f in zip(self.graphs_ids, self.graphs_output): output_path = os.path.join(basic_path, 'graph_images', '{}.png'.format(i)) pio.write_image(f, output_path)
def save_image(figure, filepath): if os.environ['PY_ENV'] == 'test': return filepath = util.smart_path(filepath) try: pio.write_image(figure, filepath) except Exception as e: orca_warn_once(e)
def get_im(fig): buf = io.BytesIO() pio.orca.config.server_url = os.getenv( 'SMART_SPACE_TRACKING_ORCA_PORT_9091_TCP_ADDR') + ":9091" pio.orca.config.use_xvfb = False pio.write_image(fig, buf) img = Image.open(buf) return np.array(img)
def save_image(fig, id, sub, sub_filter): date = dt.datetime.now().date() if not os.getcwd().split(os.sep)[-1] == str(id): change_directory(sub=sub, id=str(id), date=str(date.month) + "." + str(date.day), filter=sub_filter) try: pio.write_image(fig, str(id) + ".png") except PermissionError: print('unable to write to file')
def show(fig): import io import plotly.io as pio from PIL import Image buf = io.BytesIO() pio.write_image(fig, buf) img = Image.open(buf) img.show()
def draw_plot(self): # Draw the plot plot_figure = go.Figure(data=self.create_traces(), layout=self.define_layout()) if self.out_file != '': pio.write_image(fig=plot_figure, file=self.out_file) plotly.offline.iplot(plot_figure)
def visualize_result(self, result_dir, output_type, **kwargs): info = read_table_file(os.path.join(result_dir, "files", "info.csv")) info = info.set_index("filename") classes = read_table_file( os.path.join(result_dir, "files", "classes.csv")) embeddings = ["PCA", "ICA", "Truncated SVD", "tSNE", "UMAP"] if output_type == "pdf": from plotly import graph_objs as go, io as pio for class_label in classes.index.values: class_names = classes.loc[class_label].astype("str").values for embedding_name in embeddings: embedding_slug = embedding_name.replace(" ", "_").lower() filename = "%s_%s.csv" % (class_label, embedding_slug) embedded_df = read_table_file( os.path.join(result_dir, "files", filename)) fig = go.Figure(layout=go.Layout(title=info.loc[filename] ["plot_description"], font=dict(size=8))) color_scale = self._get_color_scales(class_names) clusters = embedded_df["k_means_clusters"].values X = embedded_df["X"].values Y = embedded_df["Y"].values for i, class_name in enumerate( list(sorted(set(class_names)))): indices = [ j for j, c in enumerate(class_names) if c == class_name ] color = color_scale[i] fig.add_scatter(x=X[indices], y=Y[indices], mode='markers', marker=dict( color=color, opacity=0.5, symbol=[ ployly_symbols[c] for c in clusters[indices] ]), name=class_name) pio.write_image(fig, os.path.join( result_dir, "plot_%s_%s.pdf" % (class_label, embedding_slug)), width=800, height=600) elif output_type == "html": raise NotImplementedError() else: raise NotImplementedError()
def test_write_image_string_bad_extension_failure(fig1): # Bad extension file_path = os.path.join(tmp_dir, "fig1.bogus") # Use file extension to infer image type. with pytest.raises(ValueError) as err: pio.write_image(fig1, file_path) assert "must be specified as one of the following" in str(err.value)
def test_write_image_string_no_extension_failure(fig1): # No extension file_path = os.path.join(tmp_dir, "fig1") # Use file extension to infer image type. with pytest.raises(ValueError) as err: pio.write_image(fig1, file_path) assert "add a file extension or specify the type" in str(err.value)
def test_write_image_string_bad_extension_failure(fig1): # Bad extension file_path = tmp_dir + 'fig1.bogus' # Use file extension to infer image type. with pytest.raises(ValueError) as err: pio.write_image(fig1, file_path + 'fig1') assert 'must be specified as one of the following' in str(err.value)
def test_write_image_string_no_extension_failure(fig1): # No extension file_path = tmp_dir + 'fig1' # Use file extension to infer image type. with pytest.raises(ValueError) as err: pio.write_image(fig1, file_path + 'fig1') assert 'add a file extension or specify the type' in str(err.value)
def plot_error_vs_iterations(self, a_solver: SolverGaussSeidelPsi): df = pd.DataFrame(data={'Iteration':a_solver.solution_iterations, 'Error':a_solver.solution_error}) fig = px.line(df, x="Iteration", y="Error", title='Solution convergence') fig.update_xaxes(title_text="Iteration") fig.update_yaxes(title_text="Error") fig.update_layout(font={'size':28}) fig.show() pio.write_image(fig, files_output_path + self.output_files_name + 'Error_vs_Iteration.png', width=2864, height=1356)
def write(self, path, **kwargs): """writes static image file, suffix dictates format""" from plotly.io import write_image fig = self.figure kwargs["width"] = kwargs.get("width", fig.layout.width) kwargs["height"] = kwargs.get("height", fig.layout.height) write_image(fig, path, **kwargs)
def TS_plotly(self,df,idx_target,idx_feature,filename_out=None): import plotly.express as px import plotly.io as pio fig = px.line(data_frame=df,x=df.columns[idx_feature], y=df.columns[idx_target]) if filename_out is not None: pio.write_image(fig, self.folder_out+filename_out, width=1080, height=720) #fig.show() return
def download(click, figure): if click > 0: download_df, str_name = load_results(figure) print(download_df) download_df.to_csv(str_name + '.csv') pio.write_image(figure, r'fig1.svg', format='svg') return ['Downloaded csv as ' + str_name + '.csv'] else: return []
def make_bar_plot_color_size(df1, df2, titles, title, ylabel, saveFig): data1 = np.nanmean(df1, axis=0) error1 = confidence_interval(df1)[1] - data1 data2 = np.nanmean(df2, axis=0) error2 = confidence_interval(df2)[1] - data2 short = False if not (type(error1) == np.ndarray): short = True error1 = [error1] error2 = [error2] data1 = [data1] data2 = [data2] fig = go.Figure() fig.add_trace( go.Bar(name='Color', marker_color='#AE3209', x=titles, y=data1, error_y=dict(type='data', array=error1))) fig.add_trace( go.Bar(name='Size', marker_color='#f3511b', x=titles, y=data2, error_y=dict(type='data', array=error2))) fig.update_layout( barmode='group', title={ 'text': title, 'y': 0.9, 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top' }, font=dict(size=15), yaxis_title=ylabel, ) fig.update_layout() fig.show() if saveFig: fig.write_html(title + ".html") if short: pio.write_image(fig, title + ".png", width=500, format="png", engine="kaleido", scale=3) else: pio.write_image(fig, title + ".png", width=1000, format="png", engine="kaleido", scale=3)
def test_write_image_writeable(fig1, format): file_name = 'fig1.' + format with open(images_dir + file_name, 'rb') as f: expected_bytes = f.read() mock_file = MagicMock() pio.write_image(fig1, mock_file, format=format, width=700, height=500) mock_file.write.assert_called_once_with(expected_bytes)
def test_write_image_string_bad_extension_override(fig1): # Bad extension file_name = 'fig1.bogus' tmp_path = tmp_dir + file_name pio.write_image(fig1, tmp_path, format='eps', width=700, height=500) with open(tmp_path, 'rb') as f: written_bytes = f.read() with open(images_dir + 'fig1.eps', 'rb') as f: expected_bytes = f.read() assert written_bytes == expected_bytes
def test_write_image_string_format_inference(fig1, format): # Build file paths file_name = 'fig1.' + format file_path = tmp_dir + file_name # Use file extension to infer image type. pio.write_image(fig1, tmp_dir + file_name, width=700, height=500) with open(file_path, 'rb') as f: written_bytes = f.read() with open(images_dir + file_name, 'rb') as f: expected_bytes = f.read() assert written_bytes == expected_bytes
def test_write_image_string(fig1, format): # Build file paths file_name = 'fig1.' + format file_path = tmp_dir + file_name pio.write_image(fig1, tmp_dir + file_name, format=format, width=700, height=500) with open(file_path, 'rb') as f: written_bytes = f.read() with open(images_dir + file_name, 'rb') as f: expected_bytes = f.read() assert written_bytes == expected_bytes
def bar_chart(self, members, is_terminal, is_root, p, score, split): fig = { "data": [ { "values": [v for v in members.values()], "labels": [k for k in members.keys()], "domain": {"x": [0, 1], "y":[0.4, 1.0]}, "hole": .4, "type": "pie", 'showlegend': True if is_root else False, 'marker': {'colors': cl.scales['5']['qual']['Set1']} }], "layout": { "margin": dict(t=50), "annotations": [ { "y": {'domain': [0, 0.2]}, "font": { "size": 18 }, "showarrow": False, "text": '', "x": 0.5, "y": 0.5 }, { "y": {'domain': [0, 0.2]}, } ] } } if is_terminal is False: self.append_table(fig, [p, score, split]) file = '/tmp/' + ("%.20f" % time.time()).replace('.', '') + '.png' pio.write_image(fig, file=file, format='png') self.files.append(file) return file