def __init__(self, figure=None, dark=False, *, num_points=150, plane=None): super().__init__(figure, num_points=num_points, plane=plane) self._layout = Layout( autosize=True, scene=dict( xaxis=dict(title="x (km)"), yaxis=dict(title="y (km)"), zaxis=dict(title="z (km)"), aspectmode="data", # Important! ), ) if dark: self._layout.template = "plotly_dark"
def get_figure(edges, nodes): edge_trace = Scatter(x=[x for x, _ in edges], y=[x for _, x in edges], line=dict(width=0.5, color='#888'), hoverinfo='none', mode='lines') node_trace = Scatter(x=[x[0] for x in nodes.values()], y=[x[1] for x in nodes.values()], customdata=[(x, y[3]) for x, y in nodes.items()], text=[x[3] for x in nodes.values()], mode='markers', hoverinfo='text', marker=dict(showscale=False, color=[x[2] for x in nodes.values()], size=15)) figure = Figure( data=[edge_trace, node_trace], layout=Layout(showlegend=False, hovermode='closest', margin=dict(b=20, l=5, r=5, t=40), xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), yaxis=dict(showgrid=False, zeroline=False, showticklabels=True), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)'), ) return figure
def visualize_data(batch, reconstructions, std, mean, viz_width=9): # denormalize ground_truth = (batch.x[:viz_width, :, :] * std) + mean for i, rec in enumerate(reconstructions): reconstructions[i] = (rec[:viz_width, :, :] * std) + mean rec_errors = [ torch.norm(ground_truth - rec, dim=2) for rec in reconstructions ] min_error = 0 max_errors = [ torch.max(torch.max(rec_err)).item() for rec_err in rec_errors ] max_error = max(max_errors) geometric_objs = [] for i in range(viz_width): for j in range(len(reconstructions) + 1): offset = [i * 0.25, -j * 0.35, 0] if j == 0: geometric_objs.append( get_geometric_object( v=np.squeeze(ground_truth[i, :, :].numpy()), f=np.squeeze(batch.face[i, :, :].numpy()), color=np.zeros(batch.x.shape[0]), color_min=min_error, color_max=max_error, offset=offset, is_first=i == 0)) else: v_pred = np.squeeze( reconstructions[j - 1][i, :, :].detach().numpy()) v_true = np.squeeze(ground_truth[i, :, :].detach().numpy()) rec_error = np.linalg.norm(v_pred - v_true, axis=1) geometric_objs.append( get_geometric_object(v=v_pred, f=np.squeeze( batch.face[i, :, :].numpy()), color=rec_error, color_min=min_error, color_max=max_error, offset=offset)) layout = Layout(autosize=True, scene=dict(aspectmode='data'), margin=dict(l=50, r=50, b=0, t=0, pad=4), scene_camera=dict(up=dict(x=0, y=1, z=0), center=dict(x=0, y=0, z=0), eye=dict(x=0, y=0, z=2)), xaxis=dict(showgrid=False), yaxis=dict(showgrid=False), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)') fig = go.Figure(data=geometric_objs, layout=layout) fig.show()
def __init__(self, figure=None, *, num_points=150, plane=None): super().__init__(figure, num_points=num_points, plane=plane) self._layout = Layout( autosize=True, xaxis=dict(title="x (km)", constrain="domain"), yaxis=dict(title="y (km)", scaleanchor="x"), shapes=[], ) self._frame = None
def makeBurstPlot(code): if not code: return waitMake('Select Country from Map', 'Current Risk Breakdown in Selected Country') code = code['points'].pop()['location'] if code else '' name = data['cnmap'][code] if code else 'Country' tempo = data['rlast'][data['rlast'].code.eq(code)] nick = tempo.nick.tolist() root = tempo.root.tolist() rate = tempo.rate.tolist() rati = tempo.rati.tolist() perc = tempo.perc.tolist() parents = [] values = [] labels = [] for n in range(41): print(nick[n], root[n], rate[n], perc[n]) if nick[n] != 'Total' and rati[n] > 0: parents += [root[n]] if root[n] != 'Total' else [None] values += [rati[n]] labels += [nick[n]] trace0 = \ Sunburst( labels = labels, parents = parents, values = values, branchvalues = 'total', ) layout = \ Layout( title = f'<b>Current Risk Breakdown in {name}</b>', xaxis_title = f'<b>Unit Risk Exposure <a href="https://docs.google.com/spreadsheets/d/1HSR3GIjPgz6KsU2DWNKDiuk5BxqXx1McbkTSyv3ZVNo">Details</a></b>', annotations = [ dict( x = 2, y = 5, xref = "x", yref = "y", text = "", showarrow = False, arrowhead = 0, ax = 0, ay = -40 )] ) return [upFigure(traces=[trace0], layout=layout, margin=(60, 0, 10, 10))]
def __init__(self, figure=None, dark=False, *, num_points=150, plane=None, unit=u.km): super().__init__(figure, num_points=num_points, plane=plane, unit=unit) self._layout = Layout( autosize=True, scene=dict( xaxis=dict(title=f"x ({self._unit})"), yaxis=dict(title=f"y ({self._unit})"), zaxis=dict(title=f"z ({self._unit})"), aspectmode="data", # Important! ), ) if dark: self._layout.template = "plotly_dark" self._draw_impulse
def makeWorldPlot(corp, area, foot): if not all([corp, area, foot]): return waitMake( 'Select Corp, Area(s), and Footprint Measure from Dropdown(s)', 'Geographical Footprint') scope = data['scope'] cnmap = data['cnmap'] tempo = scope[(scope.corporation == corp) & (scope.region.isin(area))].groupby('code').sum() tempo['country'] = tempo.index.map(cnmap) tempo['scaled'] = tempo[foot].map(np.log10) tempo['hover'] = tempo.apply( lambda x: f'{x.country} {foot.title()} : {x[foot]}', axis=1) trace0 = \ Choropleth( locations = tempo.index, z = tempo.scaled, text = tempo.hover, showscale = False, colorscale = 'purples', colorbar_bgcolor = f'rgb(255, 255, 255)', colorbar_tickprefix = f'10^', colorbar_title = f'<b># of {foot.title()}</b><br>logarithmic scale', ) layout = \ Layout( title = f'<b>Geographical Footprint of {corp} by {foot.title()}<b>', geo_projection_type = 'natural earth', geo_projection_rotation_lon = 0, geo_projection_rotation_lat = 0, geo_projection_scale = 1, geo_showocean = True, geo_showland = True, geo_showlakes = True, geo_lakecolor = 'rgb(51, 193, 255)', geo_oceancolor = 'rgb(51, 193, 255)', geo_bgcolor = 'rgb(255, 255, 255)', paper_bgcolor = BG_PAPER, plot_bgcolor = BG_PLOT, ) return [upFigure(traces=[trace0], layout=layout, margin=(60, 0, 0, 0))]
def update_graph_live(n): count_list = sorted([this for this in list(count.items()) if this[0].lower() not in set(stop_word)], key=lambda x: x[1], reverse=True, ) to_show = {count_item[0]: count_item[1] for count_item in count_list[:token_count]} word_cloud = WordCloud().generate_from_frequencies(frequencies=to_show, max_font_size=max_font_size, ) max_size = max(this[1] for this in word_cloud.layout_) min_size = min(this[1] for this in word_cloud.layout_) logger.info('cloud min count: {}'.format(min([count[this[0][0]] for this in word_cloud.layout_]))) return Figure(data=[Scatter(mode='text', text=[this[0][0] if '/' not in this[0][0] else this[0][0].split('/')[0] for this in word_cloud.layout_], hoverinfo='text', hovertext=['{}: {}'.format(this[0][0], count[this[0][0]], ) for this in word_cloud.layout_], x=[this[2][0] for this in word_cloud.layout_], y=[this[2][1] for this in word_cloud.layout_], textfont=dict( # todo make the sizes less disparate color=[float_color_to_hex(int((this[1] - min_size) * 255 / max_size), cm.get_cmap(plotly_colormap)) for this in word_cloud.layout_], size=[2 * this[1] for this in word_cloud.layout_], ))], layout=Layout(autosize=True, height=800, width=1800, xaxis=dict(showticklabels=False), yaxis=dict(showticklabels=False), ))
json.dump(all_eq_data, f, indent=4) all_eq_dicts = all_eq_data['features'] mags, lons, lats, hover_texts = [], [], [], [] for eq_dict in all_eq_dicts: mags.append(eq_dict['properties']['mag']) lons.append(eq_dict['geometry']['coordinates'][0]) lats.append(eq_dict['geometry']['coordinates'][1]) hover_texts.append(eq_dict['properties']['title']) # Map the earthqukes. data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'text': hover_texts, 'marker': { 'size': [5 * 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) ''' ## print to see that it worked print("MAGS:\n",mags[:10]) ## [:10] only prints the first ten items in the list, same as [0:10] print("\nLONS:\n", lons[:10]) print("\nLATS:\n", lats[:10]) ''' from plotly.graph_objects import Scattergeo, Layout from plotly import offline ##data = [Scattergeo(lon=lons, lat=lats)] data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'marker': { 'size': [5 * mag for mag in mags], 'color': mags, 'colorscale': 'Viridis', 'reversescale': True, # 'colorbar': { 'title': 'Magnitude' } } }] myLayout = Layout(title="Global Earthquakes") fig = {'data': data, 'layout': myLayout} offline.plot(fig, filename='global_earthquakes.html')
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) # 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')
for eq_dict in 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 data from the significant_quakes file data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'text': hover_texts, 'marker': { 'size': [5 * mag for mag in mags], 'color': mags, 'colorscale': "YlGnBu", 'reversescale': True, 'colorbar': { "title": "Magnitude" }, }, }] my_layout = Layout(title="<b>Significant Earthquakes in Last 30 Days</b>") fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename="significant_global_quakes.html")
def makeTrendPlot(code, root): if not all([code, root]): return waitMake( 'Select Country from Map, and Risk Category from Sunburst', 'Historical Stream of Selected Risk in Selected Country') code = code['points'].pop()['location'] if code else '' root = root['points'].pop()['label'] if root else '' name = data['cnmap'][code] if code else 'Country' risks = data['risks'] tempo = risks[(risks.code == code)] traces = [] nicks = risks[risks.root == root].nick.unique().tolist() nicks = risks[risks.nick == root].nick.unique().tolist() if not nicks else nicks color = [ '#6a3f39', '#a87c79', '#d6b3b1', '#d8c3b2', '#6a3f39', '#f0e6de', '#a87c79', '#d6b3b1', '#6a3f39', '#f2f5fa' ] for n, nick in enumerate(nicks[:10]): x = tempo[tempo.nick == nick].date.tolist() y = tempo[tempo.nick == nick].perc.tolist() c = color[n] t = \ { 'fill' : 'tonexty', 'line' : { # 'color' : c, 'width' : 0, 'shape' : 'spline', }, 'mode' : 'lines', 'type' : 'scatter', # 'fillcolor' : c, 'name' : nick, 'x' : x, 'y' : y, 'stackgroup': 'one' } traces.append(t) river = pd.read_csv('data/river.csv') traces_ = [] for n, c in enumerate(color): x = river[f'x'] y = river[f'y_{n}'] t = \ { 'fill' : 'tonexty', 'line' : { # 'color' : c, 'width' : 0, 'shape' : 'spline', }, 'mode' : 'lines', 'type' : 'scatter', # 'fillcolor' : c, 'x' : x, 'y' : y, } traces_.append(t) layout = \ Layout( title = f'<b>Historical Stream of {root} Risk in {name}<b>', yaxis_title = '<b>Relative Risk Exposure<b>', xaxis_title = '<b>Dates<b>', ) return [upFigure(traces=traces, layout=layout, margin=(60, 40, 40, 200))]
def index(): # data for the distribution graph genre_counts = df.groupby('genre').count()['message'] genre_names = list(genre_counts.index) # data for the subplots graph genre_unique = df['genre'].unique() plotting_df = pd.melt(df, id_vars=['genre'], value_vars=df.columns[3:]) plotting_df = plotting_df.groupby(['genre', 'variable']).sum().reset_index() # graph number 2 fig1 = make_subplots(rows=genre_unique.shape[0], cols=1, print_grid=False, subplot_titles=genre_unique) i = 1 for genre in genre_unique: data = plotting_df[plotting_df['genre'] == genre] fig1.add_trace(Bar(x=data['variable'], y=data['value'], opacity=0.5, marker=dict(color='#F1C40F')), row=i, col=1) i += 1 # cleaning the layout of the graphs layout_custom = layout.Template(layout=Layout( titlefont=dict(size=24, color='#34495E'))) fig1['layout'].update(title='Messages by genre and category', showlegend=False, template=layout_custom) fig1['layout']['yaxis1'].update(hoverformat=',d', tickformat=',d') fig1['layout']['yaxis2'].update(hoverformat=',d', tickformat=',d') fig1['layout']['yaxis3'].update(hoverformat=',d', tickformat=',d') fig1['layout']['xaxis1'].update(visible=False) fig1['layout']['xaxis2'].update(visible=False) # graph number 1 graphs = [{ 'data': [ Bar(x=genre_names, y=genre_counts, opacity=0.5, marker=dict(color='#F1C40F')) ], 'layout': { 'template': layout_custom, 'title': 'Distribution of Message Genres', 'yaxis': { 'title': "Count" }, 'xaxis': { 'title': "Genre" } } }] graphs.append(fig1) # encode plotly graphs in JSON ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)] graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder) # render web page with plotly graphs return render_template('master.html', ids=ids, graphJSON=graphJSON)
brightnesses, lats, lons = [], [], [] for fire in Bright_Fires: brightnesses.append(fire["brightness"]) lons.append(fire["longitude"]) lats.append(fire["latitude"]) data = [{ "type": "scattergeo", "lon": lons, "lat": lats, "marker": { "size": [0.035 * brightness for brightness in brightnesses], "color": brightnesses, "colorscale": "Viridis", "reversescale": True, "colorbar": { "title": "Brightness" }, }, }] Graph_legend = {"title": "Brightness"} my_layout = Layout( title="US Fires - 9/14/2020 through 9/20/2020", legend=Graph_legend, ) fig = {"data": data, "layout": my_layout} offline.plot(fig, filename="California_Fires.html")
for fire in fire_data: bright = fire['brightness'] lat = fire['latitude'] lon = fire['longitude'] if (bright > 450): brightness.append(bright) lats.append(lat) lons.append(lon) from plotly.graph_objects import Scattergeo, Layout from plotly import offline data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'marker': { 'size': 15, 'color': brightness, 'colorscale': 'Viridis', 'reversescale': True, 'colorbar': { 'title': 'Brightness' }, } }] myLayout = Layout(title="California Fires from 9/14-9/20") fig = {'data': data, 'layout': myLayout} offline.plot(fig, filename='calif_fires_9_14.html')
def main(): # get path to directory filepath = input('Path to directory (blank if PWD): ') # check if valid path if filepath != '': if not path.isdir(filepath): exit('Invalid path') data, lats, lons, flag, good, bad = [], [None, None], [None, None], False, 0, 0 # ask if user wants too show images' metadata (added for my zine) meta = input('\nShow metadata? (y/n): ') if meta.lower() in ('yes', 'y'): metaflag = True elif meta.lower() in ('no', 'n'): metaflag = False else: exit('Invalid response') # read all files in dir for file in glob(filepath + '*'): file = file.lower() # skip non-image files if not file.endswith('.jpg') and not file.endswith( '.jpeg') and not file.endswith('.png'): continue # extract Exif data from image exif = { TAGS[key]: val for key, val in Image.open(file).getexif().items() if key in TAGS } # extract GPS + datetime try: loc = exif['GPSInfo'] dt = exif['DateTimeOriginal'] good += 1 # skip if either missing except KeyError: bad += 1 continue # extract latitude and longitude lat = { 'dir': loc[1], 'deg': loc[2][0], 'min': loc[2][1], 'sec': loc[2][2] } lon = { 'dir': loc[3], 'deg': loc[4][0], 'min': loc[4][1], 'sec': loc[4][2] } # clean and print metadata if metaflag: cleanLat = str(lat['deg']) + '° ' + str(lat['min']) + '\' ' + str( lat['sec']) + '\" ' + str(lat['dir']) cleanLon = str(lon['deg']) + '° ' + str(lon['min']) + '\' ' + str( lon['sec']) + '\" ' + str(lon['dir']) print( f'File: {file} Latitude: {cleanLat} Longitude: {cleanLon} Time: {dt}' ) # calculate full coordinate with degree, minute, second truLat = float(lat['deg'] + (lat['min'] / 60.0) + (lat['sec'] / 3600.0)) truLon = float(lon['deg'] + (lon['min'] / 60.0) + (lon['sec'] / 3600.0)) # calculate mins and maxes if flag: lons[0], lons[1] = min(lons[0], truLon), max(lons[1], truLon) lats[0], lats[1] = min(lats[0], truLat), max(lats[1], truLat) # first time just assign values and flip flag else: lons[0], lons[1] = truLon, truLon lats[0], lats[1] = truLat, truLat flag = True data.append({ 'img': file, 'lat': lat, 'lon': lon, 'datetime': dt, 'truLat': truLat, 'truLon': truLon }) # not enough valid images if good <= 1: exit('Didn\'t find enough valid image files for a visualization.') print( f'\nExtracted metadata from {good} files. Unable to extract from {bad}.\n' ) # prompt for viz choice q = input( 'Please enter the number corresponding to your visualization of choice:\n1: Unsorted path\n2: Sorted path\n3: Both paths overlaid\n\n#: ' ) # validate user input while q not in ('1', '2', '3'): q = input('#: ') q = int(q) coords, sortedCoords, unSortedData = 'M ', 'M ', None # copy data, add first point if q == 1 or q == 3: unSortedData = data.copy() coords += str(unSortedData[0]['truLat']) + ',' + str( unSortedData[0]['truLon']) + ' ' # sort data, add first point if q == 2 or q == 3: data.sort(key=lambda x: x['datetime']) sortedCoords += str(data[0]['truLat']) + ',' + str( data[0]['truLon']) + ' ' # append rest of points for i in range(1, good): if q == 1 or q == 3: coords += ('L' + str(unSortedData[i]['truLat']) + ',' + str(unSortedData[i]['truLon']) + ' ') if q == 2 or q == 3: sortedCoords += ('L' + str(data[i]['truLat']) + ',' + str(data[i]['truLon']) + ' ') paths = [] # if using unsorted, append path if coords != 'M ': paths.append({'type': 'path', 'path': coords, 'line_color': '#3CB371'}) # if using sorted, append path if sortedCoords != 'M ': paths.append({ 'type': 'path', 'path': sortedCoords, 'line_color': '#6666FF' }) fig = Figure(layout=Layout(plot_bgcolor='RGBA(1,1,1,0)')) # draw axes from min to max fig.update_xaxes(range=[lats[0], lats[1]], color='#FFFFFF') fig.update_yaxes(range=[lons[0], lons[1]], color='#FFFFFF') fig.update_layout(shapes=paths) fig.show()
lat_index = header.index('latitude') bright_index = header.index('brightness') for row in reader: lons.append(row[lon_index]) lats.append(row[lat_index]) brights.append(row[bright_index]) data = [{ 'type': 'scattermapbox', 'lon': lons, 'lat': lats, 'text': ["Brightness: {}".format(bright) for bright in brights], 'marker': { 'size': 5, 'color': 'firebrick', } }] fire_layout = Layout(title={ 'text': 'Daily World Fire - MODIS', 'x': 0.5 }, mapbox={ 'style': 'satellite-streets', 'accesstoken': mapbox_access_token }) fig = {'data': data, 'layout': fire_layout} offline.plot(fig, filename='modis_world_fire.html')
class OrbitPlotter3D(_PlotlyOrbitPlotter): """OrbitPlotter3D class.""" def __init__(self, figure=None, dark=False, *, num_points=150, plane=None): super().__init__(figure, num_points=num_points, plane=plane) self._layout = Layout( autosize=True, scene=dict( xaxis=dict(title="x (km)"), yaxis=dict(title="y (km)"), zaxis=dict(title="z (km)"), aspectmode="data", # Important! ), ) if dark: self._layout.template = "plotly_dark" def _draw_point(self, radius, color, name, center=[0, 0, 0] * u.km): # We use _plot_sphere here because it's not easy to specify the size of a marker # in data units instead of pixels, see # https://stackoverflow.com/q/47086547 return self._draw_sphere(radius, color, name, center) def _draw_sphere(self, radius, color, name, center=[0, 0, 0] * u.km): xx, yy, zz = generate_sphere(radius, center) sphere = Surface( x=xx.to(u.km).value, y=yy.to(u.km).value, z=zz.to(u.km).value, name=name, colorscale=[[0, color], [1, color]], cauto=False, cmin=1, cmax=1, showscale=False, ) self._figure.add_trace(sphere) return sphere def _plot_coordinates(self, coordinates, label, colors, dashed): trace = Scatter3d( x=coordinates.x.to(u.km).value, y=coordinates.y.to(u.km).value, z=coordinates.z.to(u.km).value, name=label, line=dict(color=colors[0], width=5, dash="dash" if dashed else "solid"), mode="lines", # Boilerplate ) self._figure.add_trace(trace) return trace, [trace.line.color] def plot(self, orbit, *, label=None, color=None, trail=False): """Plots state and osculating orbit in their plane. Parameters ---------- orbit : ~poliastro.twobody.orbit.Orbit Orbit to plot. label : string, optional Label of the orbit. color : string, optional Color of the line and the position. trail : bool, optional Fade the orbit trail, default to False. """ if trail: raise NotImplementedError("trail not supported yet") return super().plot(orbit, label=label, color=color, trail=trail) @u.quantity_input(elev=u.rad, azim=u.rad, distance=u.km) def set_view(self, elev, azim, distance=5 * u.km): """Changes 3D view.""" x = distance * np.cos(elev) * np.cos(azim) y = distance * np.cos(elev) * np.sin(azim) z = distance * np.sin(elev) self._layout.update({ "scene": { "camera": { "eye": { "x": x.to(u.km).value, "y": y.to(u.km).value, "z": z.to(u.km).value, } } } }) if not self._figure._in_batch_mode: return self.show()
hover_values.append(hover_value) print(mags[:10]) print(lons[:10]) print(lats[:10]) from plotly.graph_objects import Scattergeo, Layout from plotly import offline data = [{ "type": "scattergeo", "lon": lons, "lat": lats, "text": hover_values, "marker": { "size": [5 * 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")
# Using a map as a type, lon and lat where the coordination, # Making as the bigger the magnitude the bigger the point where the EQ is, # Making a scaling color as bigger the magnitude it takes a specific color, # Naming the color scale data=[{"type": "scattergeo", "lon": lang, "lat": lat, "marker": { "size": [3*mags for mags in mag], "color":mag, "colorscale": "Viridis", "reversescale":True, "colorbar":{"title":"Magnitude"}}}] # Giving the graph a title and putting it in the middle with some modification text type and text size my_layout=Layout(title={"text": title , "y": 0.96, "x": 0.5, "xanchor": "center", "yanchor": "top"}, font=dict (family="Courier New, monospace", size=25)) # Saving the graph and running the data and the layout fig = {"data": data, "layout": my_layout} offline.plot(fig, filename="Global_Earthquake.html")
item, result[item], ) for item in labels ], mode='text', text=labels, textfont=dict( color=colors, size=16, ), x=xs, y=ys, ), layout=Layout( autosize=True, xaxis=dict(showticklabels=False), yaxis=dict(showticklabels=False), )) output_file = './' + basename(input_file).replace( '.pdf', '_word2vec.') + 'html' logger.info('saving HTML figure to {}'.format(output_file)) plot( auto_open=False, auto_play=False, figure_or_data=figure, filename=output_file, link_text='', output_type='file', show_link=False, validate=True, )
if os.path.isfile(filepath): title = ["日期", "成交股數", "成交金額", "開盤價", "最高價", "最低價", "收盤價", "漲跌價差", "成交筆數"] outputfile = open(filepath, "a", newline="", encoding="big5") outputwriter = csv.writer(outputfile) for i in range(12, 13): stock = twstock.Stock("2317") stocklist = stock.fetch(2018, i) data = [] for stock in stocklist: strdate = stock.date.strftime("%Y-%m-%d") li = [ strdate, stock.capacity, stock.turnover, stock.open, stock.high, stock.low, stock.close, stock.change, stock.transaction ] data.append(li) """if i==1: outputwriter.writerow(title) """ for dataline in (data): outputwriter.writerow(dataline) time.sleep(1) outputfile.close() pdstock = pd.read_csv(filepath, encoding="big5") pdstock["日期"] = pd.to_datetime(pdstock["日期"]) data1 = [ Scatter(x=pdstock["日期"], y=["收盤價"], name="收盤價"), Scatter(x=pdstock["日期"], y=["最低價"], name="最低價"), Scatter(x=pdstock["日期"], y=["最高價"], name="最高價") ] plot({"data": data1, "layout": Layout(title="2018年個股統計圖")}, auto_open=True)
bright = fire['brightness'] lat = fire['latitude'] lon = fire['longitude'] if(bright > 450): brightness.append(bright) lats.append(lat) lons.append(lon) ## print("BRIGHTS:\n",brightness,"\nLATS:\n",lats,"\nLONS:\n",lons) from plotly.graph_objects import Scattergeo, Layout from plotly import offline data = [{ 'type': 'scattergeo', 'lon' : lons, 'lat' : lats, 'marker': { 'size': 15, 'color': brightness, 'colorscale': 'Viridis', 'reversescale': True, 'colorbar' : {'title':'Brightness'}, } }] myLayout = Layout(title="US Fires - 09/14/2020 through 09/20/2020") fig = {'data':data, 'layout':myLayout} offline.plot(fig, filename='us_fires_9_14.html')
def makePlot_Stock(corp, ftype): if not all([corp]): return waitMake('Select Corp and Filter Type from Downdowns', 'M & A History and Relative Stock Market Performance') sdate = datetime(2000, 4, 1) edate = datetime(2020, 4, 1) manda = data['manda'] stock = yahoo(data['cdict'][corp], sdate, edate) bench = yahoo(data['cdict']['Dow'], sdate, edate) frame = pd.DataFrame() fdrop = 'Patent' space = ' ' nsize = 'Undisclosed' tempo = manda[manda.corporation.eq(corp) & manda.type.eq(ftype) & manda.announced.ge(sdate) & manda.announced.le(edate)] # tempo = manda[ manda.corporation.eq( corp)& # manda.type.eq( ftype)& # manda.buyer.str.contains( corp)& # ~manda.target.str.contains(fdrop)& # manda.announced.ge( sdate)& # manda.announced.le( edate)] frame['announce'] = tempo.announced frame['relative'] = tempo.ammount / tempo.ammount.max() * 40 frame['relative'] = frame.relative.mask(frame.relative < 5, 5) frame['hovering'] = tempo.apply( lambda x: f'Acquired {space.join(x.target.split(space)[:7])}<br>for {round(x.ammount/1000, 3) if x.ammount else nsize} Million Dollars', axis=1) frame['disclose'] = tempo.apply(lambda x: 'circle' if x.ammount else 'circle-open', axis=1) frame['palettes'] = tempo.apply(lambda x: 'seagreen' if x.ammount else 'green', axis=1) frame['position'] = -10 stock['percent'] = stock.Close / stock.Close[0] bench['percent'] = bench.Close / bench.Close[0] trace0 = \ Scatter( name = corp, x = stock.index, y = stock.percent, mode = 'lines', line_shape = 'spline', line_smoothing = 1.3, line_color = 'rgba(78,193,255,0.95)', line_width = 4, stackgroup = 'one' ) trace1 = \ Scatter( name = 'Dow Jones', x = bench.index, y = bench.percent, mode = 'lines', line_color = 'rgba(63,1,125,0.8)', line_width = 3, line_smoothing = 1.3, ) trace3 = \ Scatter( name = ftype, x = frame.announce, y = frame.position, text = frame.hovering, marker_size = frame.relative, marker_symbol = frame.disclose, marker_color = frame.palettes, marker_line_color = 'green', mode = 'markers' ) trace2 = \ Scatter( name = 'Timeline', x = [sdate, edate], y = [ -10, -10], mode = 'lines', line_color = 'black', line_width = 1, line_smoothing = 1.3, ) layout = \ Layout( title = f'<b>M & A History and Relative Stock Market Performance of {corp}</b>', yaxis_title = f'<b>Cumulative Return<br>(Multiple of Starting Value)<b>', xaxis_title = '<b>Dates<b>', yaxis_ticksuffix = 'x' ) return [ upFigure(traces=[trace0, trace1, trace2, trace3], layout=layout, margin=(60, 40, 60, 200)) ]
from dice_roll.rolling_dice import Die # Create two 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 in a histogram frequencies = [] max_result = die_1.number_side + die_2.number_side 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 two six-sided die 100 times', xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data': data, 'layout': my_layout}, filename='two_d6.html')
from plotly.graph_objects import Bar, Layout from plotly import offline from die import Die die_1 = Die(8) die_2 = Die(8) results = [] for roll_num in range(1000): result = die_1.roll() + die_2.roll() results.append(result) 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) 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 two D6 1000 times', xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data': data, 'layout': my_layout}, filename='d6_d6.html')
def makePlot_Total(code): if not all([code]): return waitMake( 'Select Country from Map', 'Prominent Risks in Selected Country vs. the Global Median') code = code['points'].pop()['location'] if code else '' name = data['cnmap'][code] if code else 'Country' risks = data['risks'] risks = risks[risks.nick != 'Total'] final = risks.date.max() latest_country = risks[risks.date.eq(final) & risks.code.eq(code)] median_country = latest_country.groupby('nick').perc.median().sort_values( ascending=False) latest_world = risks[risks.date.eq(final) & risks.nick.isin(median_country.index.tolist()[:10])] median_world = latest_world.groupby('nick').perc.median() x0 = median_country.index.tolist()[:10] y0 = median_country.values.tolist()[:10] x1 = median_world.index.tolist() y1 = median_world.values.tolist() trace0 = \ Bar( x = y0, y = x0, marker = { 'color' : 'rgba(50, 171, 96, 0.6)', 'line' : { 'color' : 'rgba(50, 171, 96, 1.0)', 'width' : 1 } }, name = f'{name}', orientation = 'h', ) trace1 = \ Bar( x = y1, y = x1, marker = { 'color' : 'rgba(170, 131, 126, 0.6)', 'line' : { 'color' : 'rgba(70, 71, 196, 1.0)', 'width' : 1 } }, name = 'Global Median', orientation = 'h', ) layout = \ Layout( title = f'<b>Prominent Risks in {name} vs. the Global Median<b>', yaxis_showgrid = False, yaxis_showline = False, yaxis_showticklabels = True, xaxis_title = '<b>Relative Risk Exposure<b>', xaxis_zeroline = False, xaxis_showline = False, xaxis_showticklabels = True, barmode = 'group', ) return [ upFigure(traces=[trace0, trace1], layout=layout, margin=(60, 40, 140, 160)) ]
frequencies.append(frequency) # print(frequencies) # Visualize the results. x_values = list(range(2, max_result + 1)) # Xaxis data = [Bar(x=x_values, y=frequencies) ] # The Plotly class Bar() needs a list of x-values, and a list of # y-values. x_axis_config = { 'title': 'Result', 'dtick': 1 } # Now that we have more bars on the histogram, Plotly’s default # settings will only label some of the bars. The 'dtick': 1 setting tells Plotly to label every tick mark y_axis_config = {'title': 'Frequency of Result'} # title of y axis my_layout = Layout( title='Results of rolling two D6 dice 1000 times', xaxis=x_axis_config, yaxis=y_axis_config) # The Layout() class returns an object that # specifies the layout and configuration of the graph as a whole offline.plot({ 'data': data, 'layout': my_layout }, filename='d6_d6.html') # This function needs a dictionary containing # the data and layout objects
for fire in fire_data: bright = fire['brightness'] lat = fire['latitude'] lon = fire['longitude'] if (bright > 450): brightness.append(bright) lats.append(lat) lons.append(lon) from plotly.graph_objects import Scattergeo, Layout from plotly import offline data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'marker': { 'size': 15, 'color': brightness, 'colorscale': 'Viridis', 'reversescale': True, 'colorbar': { 'title': 'Brightness' }, } }] myLayout = Layout(title="California Fires from 9/1-9/13") fig = {'data': data, 'layout': myLayout} offline.plot(fig, filename='calif_fires_9_1.html')