def get_bar_plot(parents, colors, labels, cnts, title, fn_bar): from plotly.offline import plot as pplot import plotly.graph_objs as pgo pplot_para = {} pplot_para['data'] = [ pgo.Bar(x=labels, y=cnts, text=parents, marker=dict(color=colors)) ] pplot_para['layout'] = pgo.Layout(title='distribution of {}'.format(title), xaxis=dict(title=title), yaxis=dict(title='frequency')) pplot(pplot_para, filename=fn_bar)
data_cols = ['Retail/Recreation', 'Workplace', 'Parks', 'Residential', 'Grocery/Pharmacy'] google_state.columns.name='Category' # State fig = px.line( google_state, x=google_state.index, y=data_cols, title='Wisconsin Google Mobility', range_y=[-90, 200], ) fig.update_layout(legend_title_text='Category') pplot( fig, filename='.\\docs\\assets\\plotly\\Mobility-Google-WI.html', include_plotlyjs='cdn', ) fig.write_image( '.\\docs\\assets\\Mobility-Google-WI.png', width=700, height=600, engine='kaleido', ) #%% Comparison category = ['Workplace', 'Retail/Recreation'] counties = ['Milwaukee County', 'Dane County', 'Brown County'] # take out whole-state
#%% Scatter plots # Case % vs overcrowding fig = px.scatter( prisons, x='Crowding %', y='Case %', title='Case % vs Crowding', text='Scatter Name', ) fig.update_traces(textposition='middle left') pplot(fig, filename='.\\docs\\assets\\plotly\\Prisons-Crowded.html', include_plotlyjs='cdn', ) save_png = '.\\docs\\assets\\Prisons-Crowding.png' fig.write_image( save_png, width=700, height=500, engine='kaleido', ) os.startfile(save_png) # Case % vs size fig = px.scatter( prisons, x='Population',
y1=1, xref='x', x0=date, x1=date)) date = date + delta fig.update_layout(shapes=dividers) fig.add_annotation(text='Christmas', x=datetime.datetime(2020, 12, 25, 0), y=1400, yanchor='bottom', xanchor='center', showarrow=False, textangle=270) pplot(fig, include_plotlyjs='cdn', filename=plotpath + '\\Christmas-WI.html') save_png = '.\\docs\\assets\\Christmas-WI.png' fig.write_image( save_png, width=700, height=340, engine='kaleido', ) os.startfile(save_png) #%% Christmas surge for Milwaukee # get milwaukee test numbers by copying html of the dashboard and scraping it # get this originally by doing a browser html inspection of the graph on the Milwaukee county dashboard, # then copying it to a text file. The tooltips of the graph are stored in "aria-label" labels, so
# take out 'variable=' part of the axis titles fig.for_each_annotation( lambda a: a.update( text=a.text.split("=")[-1], font=dict(size=15), ) ) fig.update_traces(textposition='outside') # other layout fig.update_layout(showlegend=False) pplot(fig, filename='.\\docs\\assets\\plotly\\Age-Covid.html', include_plotlyjs='cdn', ) # save_png = '.\\docs\\assets\\Age-Covid_2020-12-11.png' save_png = '.\\docs\\assets\\Age-Covid.png' fig.write_image( save_png, width=700, height=700, engine='kaleido', ) os.startfile(save_png) # interesting - ICU admissions are highest for late middle age. Elderly are # admitted to ICU lower than proportional to their hospitalization status. I # guess because it's less likely to do them any good.
# reindex on county name countiesWI = countiesWI.set_index('NAME') # sort by name countiesWI = countiesWI.sort_index() # add Region column countiesWI['Region'] = region_map # chloropleth by population from geopandas # base = countiesWI.plot(column='Region', color=colors, edgecolor='w', linewidth=0.5) # filter counties shapefile to WI, convert to JSON format string, then decode # to dictionary with json.loads() countiesJS = json.loads(countiesWI.to_json()) fig = px.choropleth(countiesWI, geojson=countiesJS, locations=countiesWI.index, color='Region', color_discrete_map=color_dict, category_orders={'Region': list(color_dict.keys())}, title='WI Regions', projection='mercator') fig.update_geos(fitbounds='locations', visible=False) fig.update_traces(marker_line_color='white') pplot( fig, filename=plotpath + '\\Map-Region.html', include_plotlyjs='cdn', )
showscale=False), row=2, col=1) fig.add_trace(go.Surface(x=X, y=Y, z=Z2, colorscale='Viridis', showscale=False), row=2, col=2) c1 = np.linspace(0.5, 2.5, nd) c2 = np.linspace(10, 20, nd) Z1 = np.zeros((nd, nd)) Z2 = np.zeros((nd, nd)) for i in range(nd): for j in range(nd): Z1[j, i] = R1.evaluate([c1[i], c2[j]]) Z2[j, i] = R2.evaluate([c1[i], c2[j]]) fig.add_trace(go.Surface(x=X, y=Y, z=Z1, colorscale='Viridis', showscale=False), row=3, col=1) fig.add_trace(go.Surface(x=X, y=Y, z=Z2, colorscale='Viridis', showscale=False), row=3, col=2) pplot(fig)
def get_band_html(vasprun_file, kpts_file): vasp = VaspRun(vasprun_file) rec_lat = vasp.recip_lat() eigval_origin = vasp.read_eigenvals()[0] origin_kpt = vasp.read_kpoints() kpts = np.dot(origin_kpt, rec_lat) kpt_path = np.zeros((np.shape(kpts)[0], 1)) kpt_path[1:] = np.linalg.norm(kpts[1:] - kpts[:-1], axis=1).reshape( (-1, 1)) kpt_path[1:] = np.cumsum(kpt_path[1:]).reshape((-1, 1)) eigval_shape = np.shape(eigval_origin) eigval = np.zeros((eigval_shape[0], eigval_shape[1] * 2)) for i in range(eigval_shape[1]): eigval[:, 2 * i:2 * i + 2] = eigval_origin[:, i, :] fermi, _, _ = vasp.read_dos() labels, high_kpts = read_kpoints(kpts_file) high_kpts = high_kpts @ rec_lat high_kpts_path = np.zeros((np.shape(high_kpts)[0], 1)) high_kpts_path[1:] = np.linalg.norm(high_kpts[1:] - high_kpts[:-1], axis=1).reshape((-1, 1)) high_kpts_path[1:] = np.cumsum(high_kpts_path[1:]).reshape((-1, 1)) fig = go.Figure() for ii in range(eigval_shape[1]): # import pdb; pdb.set_trace() fig.add_trace( go.Scatter(x=kpt_path.reshape((len(kpt_path), )), y=eigval[:, 2 * ii] - fermi, mode='lines', line=dict(color='blue', width=2))) annotations = [] for i, label in enumerate(labels): annotations.append( go.Annotation(x=high_kpts_path[i][0], y=-5, xref="x1", yref="y1", text=label, xanchor="center", yanchor="top", showarrow=False)) fig.add_trace( go.Scatter(x=[high_kpts_path[i][0], high_kpts_path[i][0]], y=[-5, 5], mode='lines', line=dict(color='black', width=1))) # In[4]: bandxaxis = go.XAxis(title="k-points", range=[0, kpt_path[-1]], showgrid=True, showline=True, ticks="", showticklabels=False, mirror=True, linewidth=2) bandyaxis = go.YAxis(title="$E - E_f \quad / \quad \\text{eV}$", range=[-5, 5], showgrid=True, showline=True, zeroline=True, mirror="ticks", ticks="inside", linewidth=2, tickwidth=2, zerolinewidth=2) bandlayout = go.Layout(title="Bands diagram", xaxis=bandxaxis, yaxis=bandyaxis, annotations=go.Annotations(annotations)) fig.update_layout(bandlayout) fig.update(layout_showlegend=False) # fig.show() # graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) # In[5]: # Get HTML representation of plotly.js and this figure plot_div = pplot(fig, output_type='div', include_plotlyjs=False) # Get id of html div element that looks like # <div id="301d22ab-bfba-4621-8f5d-dc4fd855bb33" ... > res = re.search('<div id="([^"]*)"', plot_div) div_id = res.groups()[0] # Build JavaScript callback for handling clicks # and opening the URL in the trace's customdata js_callback = """ <script> var plot_element = document.getElementById("{div_id}"); plot_element.on('plotly_click', function(data){{ console.log(data); var point = data.points[0]; if (point) {{ console.log(point.customdata); window.open(point.customdata); }} }}) </script> """.format(div_id=div_id) # Build HTML string html_str = """ <html> <body> {plot_div} {js_callback} <script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_SVG"> </script> </body> </html> """.format(plot_div=plot_div, js_callback=js_callback) return html_str, plot_div
tests['Tests 7-day'] = tests['Tests'].rolling(7).mean() tests['Positives 7-day'] = tests['Positives'].rolling(7).mean() tests['Positivity 7-day'] = tests['Positives 7-day'] / tests['Tests 7-day'] tests['Positivity'] = tests['Positives'] / tests['Tests'] tests['Positivity 7-day x10000'] = tests['Positivity 7-day'] * 10000 tests['Prevalence Index'] = np.sqrt( tests['Positives 7-day'] * tests['Positivity 7-day']) * 200 tests['Weekday'] = tests.Date.apply(lambda d: d.weekday()) tests.plot( x='Date', y=['Positives 7-day', 'Positivity 7-day x10000', 'Prevalence Index']) fig = px.bar(tests, x='Date', y=['Positives', 'Tests'], barmode='group') pplot(fig, include_plotlyjs='cdn', filename=plotpath + '\\temp.html') fig = px.line(tests, x='Date', y='Positives', color='Weekday') pplot(fig, include_plotlyjs='cdn', filename=plotpath + '\\temp.html') #%% Plot tests by result date covid.plotly_twolines( tests, 'Positivity', 'Positives', plotcolors=['violet', 'steelblue'], secondary_scale=1e4, ) covid.plotly_casetest(
# filter counties shapefile to WI, convert to JSON format string, then decode # to dictionary with json.loads() countiesJS = json.loads(countiesWI.to_json()) #%% Choropleth maps if do_choropleth: fig = px.choropleth(countiesWI, geojson=countiesJS, locations=countiesWI.index, color=plotcol, color_continuous_scale=px.colors.sequential.Blues, title='Cases by County', projection='mercator') fig.update_geos(fitbounds='locations', visible=False) pplot(fig, filename='.\\plots\\plotly\\temp.html' ) fig2 = px.choropleth(countiesWI, geojson=countiesJS, locations=countiesWI.index, color=plotcol2, color_continuous_scale=px.colors.sequential.Oranges, range_color=hosp_scale, title='Hospitalizations by County', projection='mercator') fig2.update_geos(fitbounds='locations', visible=False) pplot(fig2, filename='.\\plots\\plotly\\temp2.html' )
# # take out 'variable=' part of the axis titles # fig.for_each_annotation( # lambda a: a.update( # text=a.text.split("=")[-1], # font=dict(size=15), # ) # # ) # fig.update_traces(textposition='outside') fig.update_traces(marker_line_color='gray') # other layout # fig.update_layout(showlegend=False) pplot(fig, filename='.\\docs\\assets\\plotly\\Vaccination-Region.html', include_plotlyjs='cdn', ) save_png = '.\\docs\\assets\\Vaccination-Region.png' fig.write_image( save_png, width=700, height=550, engine='kaleido', ) os.startfile(save_png)
usa = pd.read_csv(url_all) # convert dates state['Date'] = pd.to_datetime(state['date'], format='%Y%m%d') usa['Date'] = pd.to_datetime(usa['date'], format='%Y%m%d') #%% Plot cases against total tests # remember total tests only fully populated oct 29... doesn't seem to have # caused a discontinuity though # Cases / Tests line plot covid.plotly_casetest( sourcedata=state, case_col='positiveIncrease', test_col='totalTestResultsIncrease', date_col='Date', savefile='docs\\assets\\plotly\\Cases-Tests-WI-CTP.html', ) #%% Plot WI vs. MN compare = usa.loc[usa.state.apply(lambda s: s in ['WI', 'MN'])] fig = px.line(compare, x='Date', y='totalTestResultsIncrease', color='state') pplot( fig, filename='.\\docs\\assets\\plotly\\WI-MN.html', include_plotlyjs='cdn', )