from die import Die # Create two D6 dice. die_1 = Die() die_2 = Die() # Make some rolls, and store results in a list. results = [] for roll_num in range(1000): result = die_1.roll() * die_2.roll() results.append(result) # Analyze the results. frequencies = [] max_result = die_1.num_sides * die_2.num_sides for value in range(1, max_result + 1): frequency = results.count(value) frequencies.append(frequency) # Visualize the results. x_values = list(range(1, max_result + 1)) data = [Bar(x=x_values, y=frequencies)] x_axis_config = {'title': 'Result', 'dtick': 1} y_axis_config = {'title': 'Frequency of Result'} my_layout = Layout(title='Results of multiplying two D6 dice 1000 times', xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data': data, 'layout': my_layout}, filename='d6_d6mult.html')
# Define traces to show on the chart sqrt_trace = Scatter( x=uniq_q_values, y=sqrt_q_values, marker=dict(color='#bce505'), name='sqrt(q)' ) f_calls_trace = Scatter( x=q_values, y=f_counts, mode='markers', marker=dict(size=4, opacity=0.4, symbol='x', color='#af0736'), name='calls to f' ) avg_f_calls_trace = Scatter( x=uniq_q_values, y=avg_f_counts, mode='markers', marker=dict(size=7, color='#000000'), name='average calls to f' ) data = [ sqrt_trace, f_calls_trace, avg_f_calls_trace ] layout = Layout(showlegend=True) fig = Figure(data=data, layout=layout) plot(fig)
# Create data y0 = np.random.randn(50) - 1 y1 = np.random.randn(50) + 1 # Define trace trace1 = Box(y=y0, showlegend=True, marker=dict(color='rgb(214, 12, 140)', ), name='Trace_y0') trace2 = Box(y=y1, showlegend=True, marker=dict(color='rgb(0, 128, 128)', ), name='Trace_y1') # Create chart # Output will be stored as a html file. # Whenever we will open output html file, one popup option will ask us about if want to save it in jpeg format. # Font family can be used in a layout to define font type, font size and font color for title plotly.offline.plot( { "data": [trace1, trace2], "layout": Layout(title="Colored Box Chart", font=dict(family='Courier New, monospace', size=18, color='rgb(0,0,0)')) }, filename='Colored_box_chart.html', image='jpeg')
from die import Die # Create a D6 and a D10. die_1 = Die() die_2 = Die(10) # Make some rolls, and store results in a list. results = [] for roll_num in range(50_000): result = die_1.roll() + die_2.roll() results.append(result) # print(results) # Analyze the results. frequencies = [] max_result = die_1.num_sides + die_2.num_sides for value in range(2, max_result + 1): frequency = results.count(value) frequencies.append(frequency) # Visualize the results. x_values = list(range(2, max_result + 1)) data = [Bar(x=x_values, y=frequencies)] x_axis_config = {'title': 'Result', 'dtick': 1} y_axis_config = {'title': 'Frequency of Result'} my_layout = Layout(title='Results of rolling a D6 and a D10 50000 times', xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data': data, 'layout': my_layout}, filename='d6_d10.html')
from plotly.graph_objs import Scattergeo, Layout from plotly import offline # Explore the structure of the data filename = "/Users/malte.niepel/Desktop/mniepel/ehmatthes-pcc_2e-078318e/chapter_16/mapping_global_data_sets/data/eq_data_7_day_m1.json" with open(filename) as f: all_eq_data = json.load(f) all_eq_dicts = all_eq_data["features"] print(all_eq_dicts[:10]) mags, longs, lats = [], [], [] for eq_dict in all_eq_dicts: mag = eq_dict["properties"]["mag"] long = eq_dict["geometry"]["coordinates"][0] lat = eq_dict["geometry"]["coordinates"][1] mags.append(mag) longs.append(long) lats.append(lat) # Map the earthqukes data = [Scattergeo(lon=longs, lat=lats)] my_layout = Layout(title="Global Earthquakes") fig = {"data": data, "layout": my_layout} offline.plot(fig, filename="global_earthquakes.html") print(mags[:10]) print(longs[:5]) print(lats[:5])
#!/usr/bin/env python3 import plotly from plotly.graph_objs import Scatter, Layout from sys import argv, exit fname = "" try: fname = argv[1] except: print("Digite o nome do arquivo de dados") exit(0) f = open(fname) epocas = [] mse = [] for line in f: s = line[:-1].split(',') epocas.append(int(s[0])) mse.append(float(s[1])) plotly.offline.plot({ "data": [Scatter(x=epocas, y=mse)], "layout": Layout(title="Aprendizagem: " + fname) })
lats.append(lat) # print(brights[:10]) # print(lons[:10]) # print(lats[:10]) from plotly.graph_objs import Scattergeo, Layout from plotly import offline data = [{ "type": "scattergeo", "lon": lons, "lat": lats, "marker": { "size": [0.02 * brightness for brightness in brights], "color": brights, "colorscale": "Viridis", "reversescale": True, "colorbar": { "title": "Brightness" }, }, }] Scattergeo(lon=lons, lat=lats) # taking scatterplots and putting on a map my_layout = Layout(title="Prominent US Fires") # give layout for ^ fig = {"data": data, "layout": my_layout} offline.plot(fig, filename="us_fires.html")
def st_map(self, zoom=11, style='mapbox://styles/rmetfc/ck1manozn0edb1dpmvtzle2cp', build_order=None): if self.dataset.node_station_info is None or len( self.dataset.node_station_info) == 0: raise ValueError('No station information found in dataset') import numpy as np import plotly from plotly.graph_objs import Scattermapbox, Layout mapboxAccessToken = "pk.eyJ1Ijoicm1ldGZjIiwiYSI6ImNrMW02YmwxbjAxN24zam9kNGVtMm5raWIifQ.FXKqZCxsFK-dGLLNdeRJHw" # os.environ['MAPBOX_API_KEY'] = mapboxAccessToken lat_lng_name_list = [e[2:] for e in self.dataset.node_station_info] build_order = build_order or list( range(len(self.dataset.node_station_info))) color = ['rgb(255, 0, 0)' for _ in build_order] lat = np.array([float(e[2]) for e in self.dataset.node_station_info ])[self.traffic_data_index] lng = np.array([float(e[3]) for e in self.dataset.node_station_info ])[self.traffic_data_index] text = [str(e) for e in range(len(build_order))] file_name = self.dataset.dataset + '-' + self.dataset.city + '.html' bikeStations = [ Scattermapbox( lon=lng, lat=lat, text=text, mode='markers', marker=dict( size=6, # color=['rgb(%s, %s, %s)' % (255, # # 195 - e * 195 / max(build_order), # # 195 - e * 195 / max(build_order)) for e in build_order], color=color, opacity=1, )) ] layout = Layout( title= 'Bike Station Location & The latest built stations with deeper color', autosize=True, hovermode='closest', showlegend=False, mapbox=dict(accesstoken=mapboxAccessToken, bearing=0, center=dict(lat=np.median(lat), lon=np.median(lng)), pitch=0, zoom=zoom, style=style), ) fig = dict(data=bikeStations, layout=layout) plotly.offline.plot(fig, filename=file_name)
y=[], name='Temp', stream=Stream(token=stream_token_temperature # Sets up temperature stream ), yaxis='y') trace_lightlevel = Scatter( x=[], y=[], name='Light %', stream=Stream(token=stream_token_lightlevel # Sets up Lightlevel stream ), yaxis='y2') layout = Layout( title='Sun Tracker - Temperature and Lightlevel Readings', #Labels graph yaxis=YAxis(title='Celcius'), yaxis2=YAxis(title='Light %', side='right', overlaying="y")) #Streams the data to plotly data = Data([trace_temperature, trace_lightlevel]) fig = Figure(data=data, layout=layout) print py.plot(fig, filename='Sun Tracker - Temperature and Lightlevel Readings') stream_temperature = py.Stream(stream_token_temperature) stream_temperature.open() stream_lightlevel = py.Stream(stream_token_lightlevel) stream_lightlevel.open()
for eq_dicts in all_eq_dicts: mags.append(eq_dicts['properties']['mag']) lons.append(eq_dicts['geometry']['coordinates'][0]) lats.append(eq_dicts['geometry']['coordinates'][1]) hover_text.append(eq_dicts['properties']['title']) print(mags[:10]) print(lons[:5]) print(lats[:5]) # data = [Scattergeo(lon=lons, lat=lats)] data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'text': hover_text, 'marker': { 'size': [5 * mag for mag in mags], 'color': mags, 'colorscale': 'Viridis', 'reversescale': True, 'colorbar': { 'title': 'Magnitude' } } }] my_layout = Layout(title={'text': title, 'x': 0.5}) fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename='global_earthquakes.html')
def graph_military_spending_over_time(): #Generate scatter plots for each country data = [] with open('data/SIPRI-Milex-data-1988-2015-cleaned-current-usd.csv' ) as current_usd: reader = csv.reader(current_usd) headers = next(reader, None) for row in reader: #Data unavailable, or country didn't exist at the time if ('. .' in row[13:] or 'xxx' in row[13:]): continue trace = Scatter(x=headers[13:], y=row[13:], name=row[0], fill='tonexty', line=dict(width=.5), mode='lines', textfont=dict(family='sans serif', size=30, color='#ff7f0e')) data.append(trace) #Sort scatter plots by countries with highest expenditures in 2015 data = sorted(data, key=lambda trace: float(trace.y[-1])) #Layout taken from https://plot.ly/python/figure-labels/ layout = Layout( title='Discretionary Military Spending 2000-2015', xaxis=dict(title='Year', titlefont=dict(family='Courier New, monospace', size=26, color='#7f7f7f')), yaxis=dict(title='Millions of 2015 US dollars', titlefont=dict(family='Courier New, monospace', size=26, color='#7f7f7f')), annotations=[ dict(x=2009, y=668567, xref='x', yref='y', text='Obama Takes Office; deployments in Iraq winding down', showarrow=True, arrowhead=7, ax=-120, ay=-40), dict(x=2003, y=415223, xref='x', yref='y', text='Beginning of Iraq War', showarrow=True, arrowhead=7, ax=-20, ay=-40), dict(x=2011, y=711338, xref='x', yref='y', text='Official end of Iraq War', showarrow=True, arrowhead=7, ax=0, ay=-25), dict(x=2001, y=312743, xref='x', yref='y', text='9/11; Beginning of War in Afghanistan', showarrow=True, arrowhead=7, ax=-20, ay=-40), dict(x=2014, y=609914, xref='x', yref='y', text='Official End of War in Afghanistan', showarrow=True, arrowhead=7, ax=20, ay=-40) ]) fig = Figure(data=data[len(data) - 15:], layout=layout) plot(fig, filename="images/military-spending-over-time")
mags, lons, lats, hover_texts = [], [], [], [] for eq_dict in all_eq_dicts: mag = eq_dict["properties"]["mag"] lon = eq_dict["geometry"]["coordinates"][0] lat = eq_dict["geometry"]["coordinates"][1] title = eq_dict["properties"]["title"] mags.append(mag) lons.append(lon) lats.append(lat) hover_texts.append(title) data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, "text": hover_texts, "marker": { "size": [3 * mag for mag in mags], "color": mags, "colorscale": "Bluered", "reversescale": False, "colorbar": { "title": "Magnitude" }, }, }] plot_title = all_eq_data["metadata"]["title"] my_layout = Layout(title=plot_title) fig = {"data": data, "layout": my_layout} offline.plot(fig, filename="global_earthquakes.html")
result = sum(rolls) else: result = reduce(operator.mul, rolls, 1) results.append(result) # Analyze the results. min_result = len(dice_set) if ope == 's' else 1 max_result = sum([d.num_sides for d in dice_set]) if ope == 's' else reduce( operator.mul, [d.num_sides for d in dice_set], 1) frequencies = list( [results.count(v) for v in range(min_result, max_result + 1)]) # Visualize the results. x_values = list(range(min_result, max_result + 1)) data = [Bar(x=x_values, y=frequencies)] x_axis_config = {'title': "Result", 'dtick': 1} y_axis_config = {'title': "Fequency of Result"} dice_str = ', '.join([str(d) for d in dice_set]) my_layout = Layout(title=f"Results of rolling {dice_str} {n_rolls} times", xaxis=x_axis_config, yaxis=y_axis_config) filename = dice_str = '_'.join([str(d).lower() for d in dice_set]) + f'_{n_rolls}_{ope}.html' offline.plot({ 'data': data, 'layout': my_layout }, filename=f'/mnt/f/tmp/{filename}')
brightnesses.append(brightness) date = datetime.strptime(row[5], '%Y-%m-%d') lat = lats.append(row[0]) lon = lons.append(row[1]) label = hover_texts.append(f"{date.strftime('%m-%d-%y')} - {brightness}") # Limit the data and stop the loop to prevent slow down. limit_data_row += 1 if limit_data_row == limit_data_rows: break # Map the fires. data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'text': hover_texts, 'marker': { 'size': [brightness/50 for brightness in brightnesses], 'color': brightnesses, 'colorscale': 'ylOrRd', 'reversescale': True, 'colorbar': {'title': 'Brightness'}, } }] my_layout = Layout(title='Global Fire Activity - 7 Days') fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename='Projects/DataVisualization/DownloadingData/CSV_Format/global_fires.html')
import plotly as py from plotly.graph_objs import Scatter, Layout, Figure import numpy as np import pandas as pd read = pd.read_csv('DriveLog.csv') df = read[read.driveMode == 'PATH_FOLLOWING'] startPoint = read.shape[0] - df.shape[0] startTime = df.ix[startPoint, 'sysTime'] xaxis = (df['sysTime'] - startTime ) * 10E-10 #should be 10E-9 but that makes our time 10x too long????? layout = Layout(title='DriveLog.csv graph', plot_bgcolor='rgb(230, 230,230)') #,height=1500,width=1500) def data(arg): return Scatter(x=xaxis, y=df[arg], mode='lines', name=arg) #position data leftPathPos = data('leftPathPos') leftEncoder = data('leftEncoder') rightPathPos = data('rightPathPos') rightEncoder = data('rightEncoder') #velocity data leftPathVel = data('leftPathVel') leftEncoderVel = data('leftEncoderVel') rightPathVel = data('rightPathVel') rightEncoderVel = data('rightEncoderVel')
dates.append(date) brightnesses.append(brightness) lats.append(row[0]) lons.append(row[1]) hover_texts.append(label) row_num += 1 if row_num == num_rows: break # Map the fires. data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'text': hover_texts, 'marker': { 'size': [brightness / 20 for brightness in brightnesses], 'color': brightnesses, 'colorscale': 'YlOrRd', 'reversescale': True, 'colorbar': {'title': 'Brightness'}, }, }] my_layout = Layout(title='Global Fire Activity') fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename='global_fires.html')
from plotly import offline from die import Die # Create a D6 die = Die() # MAke some rolls, and store results in a list. results = [] for roll_num in range(1000): result = die.roll() results.append(result) # Analyze the results. frequencies = [] for value in range(1, die.num_sides+1): frequency = results.count(value) frequencies.append(frequency) # Visulize the results. x_values = list(range(1, die.num_sides+1)) data = [Bar(x=x_values, y=frequencies)] x_axis_config = {'title': 'Result'} y_axis_config = {'title': 'Frequency of Result'} my_layout = Layout(title = 'Results of rolling on D6 1000 times', xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data': data, 'layout': my_layout}, filename='d6.html')
info.append(text) # Нанесение данных на карту data = [{ 'type': 'scattergeo', # Scattergeo позволяет определить данные на диаграмме карты мира 'lon': lons, # Долгота 'lat': lats, # Широта 'text': info, # Информация о месте землетрясерния при наведении мышью на маркер 'marker': { 'size': [mag * 5 for mag in mags ], # Увеличение точек землетрясений для ощещния разницы в их силе 'color': mags, # Сообщает Plotly какое значение должно использоваться для определения маркера на цветовой шкале 'colorscale': 'Viridis', # Какой цветовой диапозон должен использоваться 'reversescale': True, # Подобрать наиболее подходящий вариант True / False(по умолчанию) 'colorbar': { 'title': 'Magnitude' }, # Цветовой шкале рписваиватся имя для понимания значения каждого цвета }, }] filename_html = f"{all_eq_data['metadata']['title']}.html" my_layout = Layout(title='Global Earthquakes in 30 days') fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename=filename_html)
with open(filename) as f: reader = csv.reader(f) column_header = next(reader) print(column_header) for rec in reader: lons.append(rec[1]) lats.append(rec[0]) bright_ti4.append(rec[2]) hover_texts.append(rec[5]) # Map the earthquakes. data = [ Scattergeo( lon=lons, lat=lats, text=['Reported on : ' + hover_text for hover_text in hover_texts], marker={ 'size': 2, 'color': 'firebrick', 'colorscale': 'Viridis', 'reversescale': True, 'colorbar': { 'title': 'Magnitude' } }) ] my_layout = Layout(title='World Fires!!!') fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename='output-files/world_fires.html')
pair.append(curr_speed) pair.append(abs(delta_t.total_seconds())) combine.append(pair) Ts=curr_event #print combine total_n = 0 for i in range(len(combine)): total_n+=combine[i][1] prod=0 for i in range(len(combine)): curr_prod=(combine[i][0])*(combine[i][1]) prod=prod+curr_prod final_avg=prod/total_n final_avg=final_avg*0.001 print final_avg final_averages.append(final_avg) print final_averages plotly.offline.plot({ "data": [ Scatter(x=[1,2,4,6,8,10,12,14.16,18,20,22,24], y=final_averages) ], "layout": Layout( title="16-16 Server Client Architecture" ) })
print("Lons") print(lons) print("Lats") print(lats) from plotly.graph_objs import Scattergeo, Layout from plotly import offline data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, #'text':hover_texts, 'marker': { 'size': [0.05 * bri for bri in bris], 'color': bris, 'colorscale': 'Viridis', 'reversescale': True, 'colorbar': { 'title': 'Magnitude' } }, }] my_layout = Layout(title='California Fires') fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename='Cali_Fires.html')
def show_plot(data, title, filename='plot.html'): layout_comp = Layout(title=title) fig_comp = Figure(data=data, layout=layout_comp) plotly.offline.plot(fig_comp, filename=filename)
from plotly.graph_objs import Bar, Layout from plotly import offline #import matplotlib.pyplot as plt from random_walk import RandomWalk #while True: rw = RandomWalk(5000) rw.fill_walk() # Visualize the results x_values = list(rw.x_values) data = [Bar(x=x_values, y=rw.y_values)] x_axis_config = {'title': 'rw', 'dtick': 1} y_axis_config = {'title': 'rw'} my_layout = Layout(title='Random walk', xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({ 'data': data, 'layout': my_layout }, filename='Random walk_plotly.html') #keep_running=input("want to make another rw?(y/n)") #if keep_running=='n': #break
altcoin_coins = Scatter(x=blocks, y=calculate_coin_count(blocks), name='altcoin_coins') block_reward = Scatter(x=calculate_years(blocks), y=calculate_block_rewards(blocks), name='block_reward', xaxis='x2', yaxis='y2') data = [altcoin_coins, block_reward] layout = Layout(title='Altcoin Distribution Schedule', xaxis=dict(title='Blocks', titlefont=dict(color='rgb(148,103,189)'), tickfont=dict(color='rgb(148,103,189)'), domain=[0, .45]), xaxis2=dict(title='Year', titlefont=dict(color='rgb(148,103,189)'), tickfont=dict(color='rgb(148,103,189)'), domain=[.55, 1]), yaxis2=dict(title='Block Reward', titlefont=dict(color='rgb(253, 127, 40)'), tickfont=dict(color='rgb(253, 127, 40)'), anchor='x2', overlaying='y', side='right')) fig = Figure(data=data, layout=layout) plotly.offline.plot(fig, filename='index.html')
# Import Bibliotek import mysql.connector import pandas as pd import plotly from plotly.graph_objs import Scatter, Layout #Ustawienia bazy danych USER = "******" PASSWORD = "******" HOST = "localhost" DATABASE = "arduino" #Połączenie do bazy danych mysql = mysql.connector.connect(user=USER, password=PASSWORD,host=HOST,database=DATABASE) cur = mysql.cursor() query = cur.execute('SELECT * FROM temp') row = cur.fetchall() df = pd.DataFrame( [[ij for ij in i] for i in row] ) df.rename(columns={0: 'ID', 1: 'TEMP', 2: 'timestamp'}, inplace=True); df = df.sort_values(['timestamp'], ascending=[1]); plotly.offline.plot({ "data": [Scatter(x=df['timestamp'], y=df['TEMP'])], "layout": Layout(title="Temperatura") })
def plotClusters(data, dimensions): ''' This uses the plotly offline mode to create a local HTML file. This should open your default web browser. ''' if dimensions not in [2, 3]: raise Exception( "Plots are only available for 2 and 3 dimensional data") # Convert data into plotly format. traceList = [] for i, c in enumerate(data): # Get a list of x,y coordinates for the points in this cluster. cluster_data = [] for point in c.points: cluster_data.append(point.coords) trace = {} centroid = {} if dimensions == 2: # Convert our list of x,y's into an x list and a y list. trace['x'], trace['y'] = zip(*cluster_data) trace['mode'] = 'markers' trace['marker'] = {} trace['marker']['symbol'] = i trace['marker']['size'] = 12 trace['name'] = "Cluster " + str(i) traceList.append(Scatter(**trace)) # Centroid (A trace of length 1) centroid['x'] = [c.centroid.coords[0]] centroid['y'] = [c.centroid.coords[1]] centroid['mode'] = 'markers' centroid['marker'] = {} centroid['marker']['symbol'] = i centroid['marker']['color'] = 'rgb(200,10,10)' centroid['name'] = "Centroid " + str(i) traceList.append(Scatter(**centroid)) else: symbols = [ "circle", "square", "diamond", "circle-open", "square-open", "diamond-open", "cross", "x" ] symbol_count = len(symbols) if i > symbol_count: print("Warning: Not enough marker symbols to go around") # Convert our list of x,y,z's separate lists. trace['x'], trace['y'], trace['z'] = zip(*cluster_data) trace['mode'] = 'markers' trace['marker'] = {} trace['marker']['symbol'] = symbols[i] trace['marker']['size'] = 12 trace['name'] = "Cluster " + str(i) traceList.append(Scatter3d(**trace)) # Centroid (A trace of length 1) centroid['x'] = [c.centroid.coords[0]] centroid['y'] = [c.centroid.coords[1]] centroid['z'] = [c.centroid.coords[2]] centroid['mode'] = 'markers' centroid['marker'] = {} centroid['marker']['symbol'] = symbols[i] centroid['marker']['color'] = 'rgb(200,10,10)' centroid['name'] = "Centroid " + str(i) traceList.append(Scatter3d(**centroid)) title = "K-means clustering with %s clusters" % str(len(data)) plotly.offline.plot({"data": traceList, "layout": Layout(title=title)})
lons.append(eq_dict['geometry']['coordinates'][0]) lats.append(eq_dict['geometry']['coordinates'][1]) hover_texts.append(eq_dict['properties']['title']) # Map the eathquakes. data = [{ # I created the Scattergeo object inside the list data. Inside the list the data is structured as key-value pairs. 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'text': hover_texts, 'marker': { 'size': [3*mag for mag in mags], 'color': mags, 'colorscale': 'Hot', # There are more colorscale like --> Bluered_r, Viridis, Inferno, Hot, etc... 'reversescale': True, 'colorbar': {'title': 'Magnitude'}, }, }] title = all_eq_data['metadata']['title'] my_layout = Layout( title=title ) # I instance from a Layout class that it is conteined in plotly.graph_objs fig = { 'data': data, 'layout': my_layout } # Dictionary that conteins the data and the layout. offline.plot(fig, filename='global_earthquakes.html' ) # With offline.plot() function I can plot the data
name='top 10 TFs with p-value < 0.05', mode='markers', marker=dict(size=9, opacity=0.8), textfont=dict(family='sans serif', size=11, color='black'), text=list( map(lambda x: "%s\n%s" % ('CistromeDB:', x), final_top.loc[:, 'name_y'])), hoverinfo='text', textposition='top right') layout = Layout( title=title, xaxis=dict(title='-log10(p-value) of Gene Set 1' if labels1.strip() == '' else '-log10(p-value) of %s' % labels1, showgrid=False, titlefont=dict(family='Arial', size=20), rangemode='tozero', range=[0, xlim]), yaxis=dict(title='-log10(p-value) of Gene Set 2' if labels2.strip() == '' else '-log10(p-value) of %s' % labels2, showgrid=False, titlefont=dict(family='Arial', size=20), rangemode='tozero', range=[0, ylim]), hovermode='closest', width=850, height=650) fig = Figure(data=[top_trace0, trace1], layout=layout) plot(fig, filename='%s.html' % prefix, show_link=False, auto_open=False)
mags, lons, lats, hover_texts = [], [], [], [] for eq_dict in all_eq_dicts: mag = eq_dict['properties']['mag'] lon = eq_dict['geometry']['coordinates'][0] lat = eq_dict['geometry']['coordinates'][1] title = eq_dict['properties']['title'] mags.append(mag) lons.append(lon) lats.append(lat) hover_texts.append(title) # Map the eathquakes. data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'text': hover_texts, 'marker': { 'size': [3 * mag for mag in mags], 'color': mags, 'colorscale': 'Viridis', 'reversescale': True, 'colorbar': { 'title': 'Magnitude' }, }, }] my_layout = Layout(title='Global Earthquakes') fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename='global_earthquakes.html')
lats.append(lat) lons.append(lon) if bright > bright_min: brights.append(bright) #html map plotting from plotly.graph_objs import Scattergeo, Layout from plotly import offline data = [{ "type": "scattergeo", "lon": lons, "lat": lats, "marker": { "size": [20 for bright in brights], "color": brights, "colorscale": "Viridis", "reversescale": True, "colorbar": { "title": "Brightness" }, }, }] my_layout = Layout(title=title) fig = {"data": data, "layout": my_layout} offline.plot(fig, filename="global_fires.html")