def update_polar_chart(years): seasons = { 'winter': [12, 1, 2], 'spring': [3, 4, 5], 'summer': [6, 7, 8], 'fall': [9, 10, 11] } consumption_dict = {} for region in df_state['region'].unique(): df = frames[region] df = df[(df.index.year.isin(years))] consumption_dict[region] = {} consumption_dict[region]['summer'] = sum(df[(df.index.month.isin(seasons['winter']))].Consumption) consumption_dict[region]['spring'] = sum(df[(df.index.month.isin(seasons['spring']))].Consumption) consumption_dict[region]['fall'] = sum(df[(df.index.month.isin(seasons['summer']))].Consumption) consumption_dict[region]['winter'] = sum(df[(df.index.month.isin(seasons['fall']))].Consumption) df = pd.DataFrame([(k,k1,v1) for k,v in consumption_dict.items() for k1,v1 in v.items()], columns = ['region','season','consumption']) fig = px.bar_polar(df, r="consumption", theta="region", color="season", template="plotly_dark", color_discrete_sequence= ['#ffffb2','#fecc5c','#fd8d3c','#e31a1c']).update_layout( xaxis_showgrid=False, yaxis_showgrid=True, #autosize=False, #width=500, #height=500, paper_bgcolor=app_colors['background']).update_polars(bgcolor=app_colors['background']) return fig
def pie_chart(df: pd.DataFrame, r: str, theta: str, criteria: str = None) -> go.Figure: if criteria is not None: df = filter_records(df, criteria) if not pd.Series([theta, r]).isin(df.columns).all(): logger.log_error('columns not founded') return return px.bar_polar(df, r=r, theta=theta)
def update_output(city): dff = df.copy() dff = dff.loc[dff['town'] == city] kol_shtili = dff.loc[df['FF'] == 0].shape[0] shtil = (kol_shtili / dff.shape[0]) * 100 count = dff['FF'].shape[0] percents = [] for viter in dff['dd'].unique(): df2 = dff.loc[dff['dd'] == viter] percents.append((df2.shape[0] / (count - kol_shtili)) * 100) fig = px.bar_polar( dff, r=percents, color=percents, theta=dff['dd'].unique(), title=f"Роза вітрів у місці {city} за 2012 рік", ) fig.update_traces(hovertemplate='Середня сила вітру на %{theta} у місті ' + city + ':%{r}%') fig.update_layout( polar_radialaxis_ticksuffix='%', font_size=16, ) text = f"Відсоток штилю у місті {city}: {shtil}%" return fig, text
def plot_cyclical_datetimes( self, time_component, theta="value", r="count", **kwargs ): METRIC_NAME = "dates_cyclical." + time_component if not self.has(METRIC_NAME): return scale = { "hour": 24, "minute": 60, "second": 60, "day": 31, "weekday": 7, "quarter": 4, "month": 12, }[time_component] plotData = [ { r: metric[r], theta: metric[theta], "theta_scaled": metric[theta] * 360 / scale, } for metric in self.metrics[METRIC_NAME]["counts"] ] fig = px.bar_polar( plotData, r=r, theta="theta_scaled", hover_data=[theta], **kwargs ) fig.show()
def paint_all(self, painter, year_flag, month_flag, day_flag, hour_flag): wind_data = self.process_data(self.data, self.city, year_flag, month_flag, day_flag, hour_flag) figure = px.bar_polar(wind_data, r="frequency", theta="direction",\ color="wind_speed", template="plotly_dark",\ ) figure.update_layout({ 'plot_bgcolor': 'rgba(0, 0, 0, 0)', 'paper_bgcolor': 'rgba(0, 0, 0, 0)', }) figure.update_layout(legend=dict(font=dict(size=50))) img_bytes = figure.to_image(format="png") img = QImage() img.loadFromData(img_bytes) pixmap = QPixmap(img) pixmap = pixmap.scaled(self.width(), 1.2 * self.height(), Qt.KeepAspectRatio) painter.drawPixmap(0, 0, pixmap)
def plot_tilt(): fig = px.bar_polar(system_info, r="System size", theta="Tilt", range_theta=[0, 90], start_angle=0, direction="counterclockwise") fig.show() pio.write_html(fig, file='tilt.html', auto_open=True)
def get_wind(df2): df = px.data.wind() fig = px.bar_polar(df2, r="count", theta="direction", color="range", template="simple_white", color_discrete_sequence=px.colors.sequential.Plasma_r) return fig
def plotrose(): df = pd.read_excel('temp_test.xlsx') # u = eastward # v = northward vmagn = (df['v']**2 + df['u']**2)**0.5 angle = np.arctan2(df['u'] * -1, df['v'] * -1) angle = np.degrees(angle) dfnew = {'Direction': angle, 'Interval': vmagn} df = pd.DataFrame(data=dfnew) # df['angle'] %= 360 # df = df.round(decimals=1) df['Indexes'] = df['Interval'].apply(lambda x: num2range(x, index=True)) df['Interval'] = df['Interval'].apply(lambda x: num2range(x)) df['Direction'] = df['Direction'].apply(lambda x: num2dir(x)) print(df.head()) grp = df.groupby(["Indexes", "Direction", "Interval"]).size().reset_index(name="frequency") grp.sort_values(by='Indexes') totals = grp['frequency'].sum() grp['Percentiles'] = grp['frequency'].apply(lambda x: 100 * x / totals) grp['Percentiles'] = pd.Series( ["{0:.2f}%".format(val) for val in grp['Percentiles']], index=grp.index) print(grp.head()) # Dirs fig = px.bar_polar(grp, r='frequency', theta="Direction", hover_data=["Percentiles"], color="Interval", template="plotly_dark", color_discrete_sequence=px.colors.sequential.Plasma_r, category_orders={ "Direction": [ 'N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW' ] }) #fig.show() graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return graphJSON
def plot_rose(df: pd.DataFrame, r, theta, hover_data={}, labels={}, color=Color.RED) -> FigureWidget: """ Draws rose plot figure and returns it """ fig = px.bar_polar( df, r=r, theta=theta, labels=labels, start_angle=0, template='ggplot2', hover_data=hover_data, direction='counterclockwise', color_discrete_sequence=[color] ) return fig
def bar_polar_price_distribution(dataset, kw='bottles', x='price', hover_name="website", title=None): data = dataset[dataset['keyword'] == kw] fig = px.bar_polar(data_frame=data, r=x, title=title, width=500, height=500, color=x, hover_name=hover_name) return fig.to_json()
def data(winddatadf, powercurvedf): st.write('''## Data Visualisation''') st.write('It makes it simple to have a peek in your data') if winddatadf is not None and powercurvedf is not None: # Simple dataframe display cols = st.beta_columns(2) cols[0].write('''### winddata dataframe''') cols[0].write(winddatadf) cols[1].write('''### powerdata dataframe''') cols[1].write(powercurvedf) # PowerCurve Display st.write('''### Power Data plot''') # Only a subset of options make sense x_options = powercurvedf.columns y_options = powercurvedf.columns # Allow use to choose cols = st.beta_columns(2) x_axis = cols[0].selectbox('Choose Value for X axis', x_options) y_axis = cols[1].selectbox('Choose Value for y axis', y_options) # plot the value st.write(x_axis, ' vs ', y_axis) fig = px.scatter(powercurvedf, x=x_axis, y=y_axis, hover_name='Wind Speed (m/s)') st.plotly_chart(fig, use_container_width=True) # WindRose st.write('''### Wind Rose Diagram''') fig1 = px.bar_polar( winddatadf, r="sped", theta="drct", template="plotly_dark", color_discrete_sequence=px.colors.sequential.Plasma_r) st.plotly_chart(fig1, use_container_width=True) else: st.error( 'File Not uploaded yet. Please upload the power and wind data first in order to visualize them' )
def updateWindRose(dep_or_arr, datetime_lower, datetime_upper): # Call API with the parameter call_API = flask_IP + "/windDirection?" call_API = call_API + "dep_or_arr=" + dep_or_arr call_API = call_API + "&datetime_lower=" + str(datetime_lower) + " 00:00" call_API = call_API + "&datetime_upper=" + str(datetime_upper) + " 23:59" response = requests.get(call_API).json() df = pd.DataFrame(response) fig = px.bar_polar(df, r="count", theta="card_dir", color="binned_wind", template="plotly_white", color_discrete_sequence=px.colors.sequential.Plasma_r) fig.update_layout( legend=dict(title="Wind Speed (knots)", traceorder="grouped")) return fig
def get_fig_polar_bar(df): """ get the fig polar bar layout :param df: :return: """ sess_counts = df.session_count.tolist() # r, _ = np.mgrid[1:7:7j, 0:(360 / 7 * 6):7j] r = np.array([["week " + str(w - 2) for w in range(7)] for h in range(7)]).transpose() theta = np.array([['Monday'] * 7, ['Tuesday'] * 7, ['Wednesday'] * 7, ['Thursday'] * 7, ['Friday'] * 7, ['Saturday'] * 7, ['Sunday'] * 7]).transpose() # take data of weeks in march from 03-02 to 03-29 color = sess_counts[1:29] color = np.asarray(color) whitecolor = np.zeros(21, dtype=int) color = np.append(whitecolor, color) fig = px.bar_polar( r=r.ravel(), theta=theta.ravel(), color=color.ravel(), title="Radical Weekly Wifi Connection Periodic Viz", labels={1: "cool"}, start_angle=360 / 14, color_continuous_scale=[ "rgb(255, 255, 255)", "#fbe6c5", "#f5ba98", "#ee8a82", "#dc7176", "#c8586c", "#9c3f5d", "#70284a", ] # color from px.colors.carto.Buryl ) fig.update_traces(text=np.mgrid[6.5:7:7j]) fig.update_layout(polar_bargap=0, polar=dict(radialaxis=dict(showticklabels=False))) return fig
def parse_contents(contents, filename, delim, dec, velcol, dircol, dirlabels, vlim, unit_from, unit_to, valid_data): content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) try: if 'csv' in filename: # Assume that the user uploaded a CSV file df = pd.read_csv(io.StringIO(decoded.decode('utf-8')), delimiter=delim, decimal=dec) wr, dfcomp, Ncalm, N, n = processcsv(df, velcol, dircol, dirlabels, vlim, unit_from, unit_to, bool(valid_data)) msg = infomsg(N, n, Ncalm) fig = px.bar_polar( wr, r='Freq', theta='Dir', color='V', width=900, height=700, color_discrete_sequence=px.colors.sequential.Viridis) fig.update_layout(font_size=22, font_color="black", legend_title='V(' + unit_to + ')') #elif 'xls' in filename: # Assume that the user uploaded an excel file #df = pd.read_excel(io.BytesIO(decoded)) except Exception as e: print(e) return html.Div(['There was an error processing this file.']) return html.Div([ #html.H5(filename), dcc.Graph(figure=fig), html.Hr(), html.Div(msg) ])
def get_fig_polar_bar_hourly(df): """ get the fig polar bar layout :param df: :return: """ sess_counts = df.session_count.tolist() r = np.array([["March " + str(d - 1) for d in range(33)] for h in range(24)]).transpose() theta = np.array([[str(h) + "h" for h in range(24)] for d in range(33)]) # take data of hours color = sess_counts # 24*31 color = np.asarray(color) whitecolor = np.zeros(48, dtype=int) color = np.append(whitecolor, color) fig = px.bar_polar( r=r.ravel(), theta=theta.ravel(), color=color.ravel(), title="Radical Hourly Wifi Connection Periodic Viz", start_angle=360 / 48, color_continuous_scale=[ "rgb(255, 255, 255)", "#fbe6c5", "#f5ba98", "#ee8a82", "#dc7176", "#c8586c", "#9c3f5d", "#70284a", ] # color from px.colors.carto.Buryl ) fig.update_layout(polar_bargap=0, polar=dict(radialaxis=dict(showticklabels=False))) return fig
wind, r="frequency", theta="direction", color="strength", line_close=True, color_discrete_sequence=px.colors.sequential.Plasma[-2::-1], ) fig.write_html(os.path.join(dir_name, "line_polar.html")) import plotly.express as px wind = px.data.wind() fig = px.bar_polar( wind, r="frequency", theta="direction", color="strength", template="plotly_dark", color_discrete_sequence=px.colors.sequential.Plasma[-2::-1], ) fig.write_html(os.path.join(dir_name, "bar_polar.html")) # #### Maps import plotly.express as px carshare = px.data.carshare() fig = px.scatter_mapbox( carshare, lat="centroid_lat", lon="centroid_lon", color="peak_hour",
marker=dict(color='#e84a5f'), ) very_bad = go.Bar( x=health_data['country'], y=health_data['prct_health_verybad'], name='Very Bad Health', marker=dict(color='#2a3b36'), ) data = [very_good, good, fair, bad, very_bad] layout = go.Layout(title='Health in Europe (%)', barmode='relative') fig_health_data = go.Figure(data=data, layout=layout) # pollution fig_pollution = px.bar_polar(euro_stats_data, r="prct_rpt_pollution", theta="country", color="prct_rpt_pollution", title="Percent Reported Pollution in Europe") # life expectancy trace = [ go.Choropleth(colorscale='greens', locationmode='country names', locations=life_expectation_data['country'], text=life_expectation_data['country'], z=life_expectation_data['life_expect']) ] layout = go.Layout(title='Life Expectancy in Europe (%)', geo=go.layout.Geo(scope='europe', showcountries=True))
pk_plot.update_layout(legend=dict( orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)) st.plotly_chart(pk_plot, config=config, use_container_width=True) else: st.markdown("### Sem dados para o período selecionado.") if not df_wind.empty: st.title("Dados de Vento") st.write(df_wind.astype('object')) wind_fig = px.bar_polar( df_wind, r='Wspd', theta='Wind_Dir', template='plotly_dark', color_discrete_sequence=px.colors.sequential.Plasma_r, ) wind_fig.update_layout( height=plot_height + 100, width=plot_width, title=dict( text= '<b>Velocidade (nós) e Direção Média para o Período Selecionado</b>', font=dict(family='Times New Roman', size=18))) st.plotly_chart(wind_fig, config=config, use_container_width=True) st.markdown("---")
def make_figure(df,pa): df_circ=df.copy() r=pa["angvals"] print(r) theta=pa["radvals"] print(theta) color=pa["groupval"] print(color) ## Fit the data into the model pa_={} for n in ["fig_width","fig_height"]: if pa[n] == "": pa_[n]=None else: pa_[n]=float(pa[n]) for n in ["angular_grid","angular_line","angular_ticklabels","radial_grid","radial_line","radial_visibility","radial_ticklabels"]: if pa[n] in ["off", ".off"]: pa_[n]=False else: pa_[n]=True for n in ["barnorm_val", "angular_ticks", "radial_tickside"]: if pa[n] == "None": pa_[n] = "" else: pa_[n] = pa[n] color_discrete_sequence_=[] if str(pa["groupval"]) == "None": colorv=None print(pa["bar_colour_val"]) color_discrete_sequence_.append( pa["bar_colour_val"] ) elif str(pa["groupval"]) != "None": colorv=str(color) for group in pa["list_of_groups"]: PA_=[ g for g in pa["groups_settings"] if g["name"]==group ][0] barColor=PA_["bar_colour_val"] color_discrete_sequence_.append(barColor) print(color_discrete_sequence_) fig = px.bar_polar(df_circ, r=str(r), theta=str(theta), color=colorv, color_discrete_sequence=color_discrete_sequence_, ## Fix according to groups/colors barnorm=pa_["barnorm_val"], barmode=pa["barmode_val"], direction=pa["direction_val"], start_angle=int(pa["start_angle"]), title=pa["title"]) fig.update_layout(width=pa_["fig_width"], height=pa_["fig_height"], template="plotly_white", legend = dict(bgcolor = pa["legend_bgcolor"], bordercolor=pa["legend_bordercolor"], borderwidth=float(pa["legend_borderwidth"]), font={"color":"black","family":"sans serif", "size":int(pa["legend_title_font"])}, orientation=pa["legend_orientation"], title={"text":"group","font":{"color":"black","size":int(pa["legend_text_font"]), "family":"sans serif"}}), font=dict(color="black", family="sans serif", size=int(pa["plot_font"])), title=dict(font={"family":"sans serif","size":int(pa["titles"]),"color":pa["title_color"]}, xanchor="center", x=0.5), polar_bargap=float(pa["polar_bargap"]), polar_barmode=pa["polar_barmode"], polar_bgcolor=pa["polar_bgcolor"], polar_hole=float(pa["polar_hole"]), paper_bgcolor=pa["paper_bgcolor"], polar_angularaxis=dict(showgrid=pa_["angular_grid"], gridcolor=pa["angular_gridcolor"], gridwidth=float(pa["angular_gridwidth"]), showline=pa_["angular_line"], linecolor=pa["angular_linecolor"], linewidth=float(pa["angular_linewidth"]), showticklabels=pa_["angular_ticklabels"], tickcolor=pa["angular_tickcolor"], ticklen=float(pa["angular_ticklen"]), tickangle=float(pa["angular_tickangle"]), tickwidth=float(pa["angular_tickwidth"]), ticks=pa_["angular_ticks"]), polar_radialaxis=dict(showgrid=pa_["radial_grid"], gridcolor=pa["radial_gridcolor"], gridwidth=float(pa["radial_gridwidth"]), showline=pa_["radial_line"], linecolor=pa["radial_linecolor"], visible=pa_["radial_visibility"], linewidth=float(pa["radial_linewidth"]), angle=float(pa["radial_angle"]), tickangle=float(pa["radial_tickangle"]), ticklen=float(pa["radial_ticklen"]), tickwidth=float(pa["radial_tickwidth"]),tickcolor=pa["radial_tickcolor"], showticklabels=pa_["radial_ticklabels"], ticks=pa_["radial_tickside"]), ) return fig
import plotly.express as px df = px.data.wind() # 三维数据,风向,强度,频率 # 频率对应半径,角度对应风向,颜色对应强度 fig = px.bar_polar(df, r='frequency', theta='direction', color='strength', template='plotly_dark', color_discrete_sequence=px.colors.sequential.Plasma_r) fig.show()
def update_graph(sol): sol_df = df[df['sol'] == sol] #fig = px.bar(x=sol_df['ct']) fig = px.bar_polar(r=sol_df['ct'], theta=sol_df['compass_point']) return fig
import plotly.express as px import pandas as pd df = pd.read_csv('wind_dat_sorted.csv') fig = px.bar_polar(df, r="frequency", theta="direction", \ color="strength", template="plotly", \ color_discrete_sequence= px.colors.sequential.Plasma_r) #fig.show() import os if not os.path.exists("images"): os.mkdir("images") fig.write_image("images/plotly_rose.png")
return 180 elif row["aspect"] == 'SW': return 225 elif row["aspect"] == 'W': return 270 elif row["aspect"] == 'NW': return 315 else: return null rose_scatter = rose_scatter.assign(order=rose_scatter.apply(set_order, axis=1)) rose_scatter #group by aspect of occurrence count_aspect = pd.DataFrame( rose_scatter.groupby('order').count()['avalanche']).reset_index() count_aspect = count_aspect.rename(columns={ "avalanche": "Count", "order": "Degrees" }) count_aspect fig = px.bar_polar(count_aspect, r=count_aspect['Count'], theta=count_aspect['Degrees'], color="Count", template="ggplot2") fig.update_layout(title_text="Avalanches by Aspect (2009-2020)") fig.show()
fig3 = go.Figure(go.Indicator( mode="number+delta", value=df.Active.sum(axis=0), domain={'x': [0, 1], 'y': [0, 1]}, title={ 'text': "Latest Active Cases", 'font': { 'size': 30,'family': 'Overpass' } })) fig3.update_layout(paper_bgcolor="#121212", font={ 'color': "tomato", 'size':26, 'family': "Overpass" }) fig4 = px.bar_polar(df, r='C.F.R', color="C.F.R", theta=af.Region, width=950, template="plotly_dark", color_continuous_scale=cl.coolwarm, title='Case Fatality Ratio in African Regions', height=500) layout = html.Div([ dbc.Row([html.Div([ dbc.Col(html.Div([ dcc.Graph(id='Chart10', figure=fig3, animate=True, config={ 'showTips': True, 'responsive': True, 'displaylogo':False })], style={ 'color': '#ffffff', 'font-variant': 'small-caps',
locations='COUNTRY', color='Value', color_continuous_scale=px.colors.sequential.Greys, range_color=(util.Value.min(), util.Value.max()), scope="europe", color_discrete_map=colors['background'], animation_frame='Year', labels={'unemp': 'unemployment rate'}) fig_2.update_layout(plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], font_color=colors['text']) fig_3 = px.bar_polar(util, r="Value", theta="Country", color="Value", template='ggplot2', color_continuous_scale=px.colors.sequential.amp, color_discrete_map=colors['background']) fig_3.update_layout(plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], font_color=colors['text']) row_1 = dbc.Row( style={ 'backgroundColor': colors['background'], 'width': '100%' }, children=[ dbc.Col(dbc.FormGroup([ html.H1(children="Consommation d'alcool en Europe",
def iplot_bar_polar(self, theta, color, r='auto', template='xgridoff', color_continuous_scale='auto', **kwds): """ It uses plotly.express.bar_polar. In a polar bar plot, each row of 'color' is represented as a wedge mark in polar coordinates. Parameters ---------- theta: str wf.data colum with the directions in degrees (0 - 360) color: str wf.data colum with the data to plot with colors r: str wf.data column with the data to use as a radium. If r = 'auto', r is the counts of 'theta' en each direction. template: str Plotly express style templates. Options: 'ggplot2' 'seaborn' 'simple_white' 'plotly' 'plotly_white' 'plotly_dark' 'presentation' 'xgridoff' 'ygridoff' 'gridon' 'none' color_continuous_scale: plotly.express.sequential View https://plotly.com/python/colorscales/. If color_continuous_scale = 'auto', color_continuous_scale = px.colors.sequential.Rainbow **kwds: plotly.express.bar_polar arguments Returns ------- fig: plotly.graph_objects.Figure """ if color_continuous_scale == 'auto': color_continuous_scale = px.colors.sequential.Rainbow df = self.data.copy() # Create directions df['direction'] = 'N' df.loc[df[theta].between(11.25, 33.75), 'direction'] = 'NNE' df.loc[df[theta].between(33.75, 56.25), 'direction'] = 'NE' df.loc[df[theta].between(56.25, 78.75), 'direction'] = 'ENE' df.loc[df[theta].between(78.75, 101.25), 'direction'] = 'E' df.loc[df[theta].between(101.25, 123.75), 'direction'] = 'ESE' df.loc[df[theta].between(123.75, 146.25), 'direction'] = 'SE' df.loc[df[theta].between(146.25, 168.75), 'direction'] = 'SSE' df.loc[df[theta].between(168.75, 191.25), 'direction'] = 'S' df.loc[df[theta].between(191.25, 213.75), 'direction'] = 'SSW' df.loc[df[theta].between(213.75, 236.25), 'direction'] = 'SW' df.loc[df[theta].between(236.25, 258.75), 'direction'] = 'WSW' df.loc[df[theta].between(258.75, 281.25), 'direction'] = 'W' df.loc[df[theta].between(281.25, 303.75), 'direction'] = 'WNW' df.loc[df[theta].between(303.75, 326.25), 'direction'] = 'NW' df.loc[df[theta].between(326.25, 348.75), 'direction'] = 'NNW' new_index = [ 'N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW' ] # Create serie of counts for directions s_dir = df['direction'].value_counts() s_dir.rename('frequency', inplace=True) # Create mean of directions df_mean = df.groupby(['direction']).mean() df_work = pd.merge(s_dir, df_mean[color], right_index=True, left_index=True) if r != 'auto': df_work = pd.merge(df_work, df_mean[r], right_index=True, left_index=True) df_work = df_work.reindex(new_index) df_work.reset_index(inplace=True) df_work.rename(columns={'index': 'direction'}, inplace=True) df_work[color] = df_work[color].fillna(0) df_work.loc[df_work[color] == 0, 'frequency'] = 0 if r == 'auto': r = 'frequency' try: labels = { color: f'{self.vocabulary[color]["long_name"]} ({self.vocabulary[color]["units"]})' } except KeyError: labels = None fig = px.bar_polar(df_work, r=r, theta="direction", color=color, color_continuous_scale=color_continuous_scale, template=template, labels=labels) return fig
def polar_plot(): # merged = pd.merge(orders[['zipcode']], # zipcounty[['zipcode', 'latitude', 'longitude']], # on='zipcode', how='inner') # # merged = merged.drop_duplicates(keep='first') # # bearings_list = [] # # for i in list(zip(merged['latitude'], merged['longitude'])): # ptA = (37.0902, -95.7129) # bearings_list.append(calculate_initial_compass_bearing(ptA, i)) # # merged['bearings'] = bearings_list # # merged['polar'] = pd.cut(merged['bearings'], 16, labels=['N', 'NNE', 'NE', 'ENE', # 'E', 'ESE', 'SE', 'SSE', # 'S', 'SSW', 'SW', 'WSW', # 'W', 'WNW', 'NW', 'NNW']) # # orders['orderyear'] = pd.to_datetime(orders['orderdate']).dt.year # # merged_1 = pd.merge(orders[['orderyear', 'campaignid', 'zipcode', 'totalprice']], # campaigns[['campaignid', 'channel']], # on='campaignid', how='inner') # # merged_2 = pd.merge(merged_1, zipcounty[['zipcode', 'latitude', 'longitude']], on='zipcode') # # z = merged_1.groupby(['zipcode', 'channel', 'orderyear'])['totalprice'].mean() # # u = z.unstack().fillna(0).stack().reset_index() # # u.columns = ['zipcode', 'channel', 'orderyear', 'TotalSpent'] # # #z = pd.DataFrame(z) # # #z = z.reset_index() # # final = pd.merge(u, merged[['zipcode', 'polar']], on='zipcode', how='inner') # # mean_final = final.groupby(['polar', 'channel', 'orderyear'])['TotalSpent'].mean() # # mean_final = mean_final.reset_index() # # mean_final = mean_final.sort_values(by=['orderyear', 'polar']) # # mean_final.to_csv('./polar_plot.csv', index=False) mean_final = pd.read_csv('./polar_plot.csv') fig = px.bar_polar( mean_final, r="TotalSpent", theta="polar", color="channel", animation_frame='orderyear', color_discrete_sequence=px.colors.colorbrewer.Set3, category_orders={'Year': [2010, 2011, 2012, 2013, 2014, 2015, 2016]}, labels={ 'orderyear': 'Year', 'channel': 'Channel', 'TotalSpent': 'Total revenue ($)', 'polar': 'US region' }) #fig = fig.for_each_trace(lambda t: t.update(name=t.name.replace("channel=", ""))) fig = fig.update_layout( showlegend=False, margin=dict(l=30, r=30, t=20, b=20), yaxis=go.layout.YAxis( title=go.layout.yaxis.Title(text="Total revenue ($)", ))) return fig
wind, # 数据集 r="frequency", # 半径 theta="direction", # 角度 color="strength", # 颜色 line_close=True, # 线性闭合 color_discrete_sequence=px.colors.sequential.Plasma_r) # 颜色变化 fig.show() # In[38]: fig = px.bar_polar( wind, # 数据集 r="frequency", # 半径 theta="direction", # 角度 color="strength", # 颜色 template="plotly_dark", # 主题 color_discrete_sequence=px.colors.sequential.Plasma_r) # 颜色变化 fig.show() # ## 选择颜色 # In[39]: px.colors.qualitative.swatches() # In[40]:
def update_grafico_2(n_clicks, cantidad_sensores, hora, tipo_sensor, sensor, sensor_multi, fecha, ventana_tiempo, ejes, eje): if len(ejes) < 1: ejes.append('x') if fecha != None: if str(str(fecha).split(sep='T')[0]) == str( str(datos.fecha_inicial(tipo_sensor, eje)).split(sep=' ')[0]): #fecha = dt.strptime(str(str(fecha).split(sep='T')[0]) + ' ' + str(str(datos.fecha_inicial()).split(sep=' ')[1]),'%Y-%m-%d %H:%M:%S') fecha = dt.strptime( str(str(fecha).split(sep='T')[0]) + ' ' + datos.crear_hora(hora), '%Y-%m-%d %H:%M:%S') else: fecha = dt.strptime( str(str(fecha).split(sep='T')[0]) + ' ' + datos.crear_hora(hora), '%Y-%m-%d %H:%M:%S') else: fecha = datos.fecha_inicial(tipo_sensor, eje) #Se inicializan variables df = pd.DataFrame() fig_2 = go.Figure() if n_clicks >= 0: fecha_ini_titulo, fecha_fin_titulo = datos.fecha_titulo( fecha, ventana_tiempo) #Dependiendo del tipo de sensor se crean visualizaciones distintas if tipo_sensor == 'weather-station': #Aqui se crea el histograma circular que contine datos de la direccion y velocidad del viento dir = datos.datos_ace(dt(2008, 4, 1, 0, 38, 3), ventana_tiempo, 'dir_viento')['dir_viento'].tolist() vel = datos.datos_ace(dt(2008, 4, 1, 0, 38, 3), ventana_tiempo, 'vel_viento')['vel_viento'].tolist() tmp1 = collections.Counter(dir) ini, fin = datos.rangos(tmp1) rr, tt = datos.datos_por_rango( pd.DataFrame({ 'dir_viento': dir, 'vel_viento': vel }), ini, fin) dff = pd.DataFrame({'Dirección': tt, 'Velocidad (m/s)': rr}) fig_2 = px.bar_polar( dff, r="Velocidad (m/s)", theta="Dirección", color_discrete_sequence=px.colors.sequential.Plasma_r) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) fig_2.update_layout( title={ 'text': "Dirección y Velocidad (m/s) del viento durante " + str(titulo_OHLC) + " " }) elif tipo_sensor == 'Acelerometro': if cantidad_sensores == '1-sensor': # La variable df contiene el dataframe que se utiliza para generar el histograma # Aqui se crea el histograma trace_sec2 = [] colors = ['#e6194b', '#3cb44b', '#ffe119'] count = 0 for e in ejes: start_time = time() df = datos.datos_ace(fecha, ventana_tiempo, sensor, e) start_time = time() #fig_2 = go.Figure(data=[go.Histogram(x=df[sensor],showlegend=False)]) trace_sec2.append( go.Histogram(x=df[sensor], showlegend=True, marker_color=colors[count], name=datos.traductor_nombre(sensor) + ' eje: ' + str(e))) count = count + 1 fig_2 = go.Figure(data=trace_sec2) elapsed_time = time() - start_time print( "Tiempo Transcurrido crear Histograma: %0.1f seconds." % elapsed_time) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) fig_2.update_layout( title="Frecuencia de datos cada " + str(datos.titulo_freq_datos(ventana_tiempo)) + " del " + str(datos.traductor_nombre(sensor)) + "<br>durante " + str(titulo_OHLC) + "<br>(" + fecha_ini_titulo + " - " + fecha_fin_titulo + ")", yaxis={"title": "Frecuencia (N° de Datos)"}, xaxis={"title": "Aceleración (cm/s²)"}, bargap=0.1, ) else: #Listas que conteneran cada trace generado por cada dataframe creado para poder visualizarlos en una grafica trace_sec2 = [] #colores para las graficas colors = [ '#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', '#808080', '#ffffff', '#000000' ] count = 0 #por cada sensor seleccionado se crean df for sen in sensor_multi: df = datos.datos_ace(fecha, ventana_tiempo, sen, eje) # Aqui se crea el histograma trace_sec2.append( go.Histogram(x=df[sen], showlegend=True, marker_color=colors[count], name=datos.traductor_nombre(sen))) count = count + 1 fig_2 = go.Figure(data=trace_sec2) titulo_OHLC = datos.titulo_OHLC(ventana_tiempo) fig_2.update_layout( title="Frecuencia de datos cada " + str(datos.titulo_freq_datos(ventana_tiempo)) + "<br>durante " + str(titulo_OHLC) + "<br>(" + fecha_ini_titulo + " - " + fecha_fin_titulo + ")", yaxis={"title": "Frecuencia (N° de Datos)"}, xaxis={"title": "Aceleración (cm/s²)"}, bargap=0.1, ) return fig_2
y="imdb_rating", color='title', title="IMDB Show Rating (in descending order)", labels=labels, template="none", color_discrete_sequence=px.colors.qualitative.Plotly) num_slices = 11 theta = [(i + 1.5) * 360 / num_slices for i in range(num_slices)] width = [360 / num_slices for _ in range(num_slices)] width fig3 = px.bar_polar(df_episodes, r="season", theta="show_title", color="show_title", title="Episodes per Show", template="none", color_discrete_sequence=px.colors.qualitative.Plotly) fig1.update_layout( # plot_bgcolor=colors['background'], # paper_bgcolor=colors['background'], font_color=colors['text'], height=800, xaxis={'categoryorder': 'total descending'}) fig1.update_yaxes(range=[8, 10]) fig3.update_layout( polar_radialaxis_ticks="",