def plotly_polar_scatterplot_chart(): """ Do something similar to a1/e_/process_life_expectancy_dataset, but don't drop the latitude and longitude. Use these two values to figure out the theta to plot values as a compass (example: https://plotly.com/python/polar-chart/). Each point should be one country and the radius should be thd value from the dataset (add up all years and feel free to ignore everything else) """ # Reading the required dataframe le_df = read_dataset(Path('..', '..', 'life_expectancy_years.csv')) # Processing the dataframe for fitting it into visualization le_df = le_df.dropna() le_df['nations'] = le_df['country'] temp_df = le_df.loc[:, le_df.columns != 'country'] le_df['total'] = temp_df.sum(axis=1) le_df['nations'] = le_df['country'] ge_df = read_dataset(Path('..', '..', 'geography.csv')) final_df = pd.concat([le_df.set_index('country'), ge_df.set_index('name')], axis=1, join='inner') final_df = final_df[['nations', 'Latitude', 'Longitude', 'total']] # Plotting the data fig = px.scatter_polar(final_df, r="total", theta="Longitude") return fig
def update_figure(patient): # one_day = data_prep.clean('3012') # fig = px.scatter_polar(one_day, r='n_day', theta='Total Minutes', color='mod desc', # hover_data=['Date','Time'],size='size', size_max=3.5,opacity=0.8, # labels= {'n_day':'wtf_m8'}) one_day = df[df['patient_id'] == patient] fig = px.scatter_polar(one_day, r='n_day', theta='minutes', color='mod_desc', hover_data=['Date', 'Time'], size='size', size_max=3.6, opacity=1.0, labels={'Date': 'date'}, range_r=[-10, 150], height=800, template={ 'layout': { 'polar': { 'angularaxis': { 'tickmode': 'array', 'tickvals': list(range(0, 360, 15)), 'ticktext': ticktext }, 'radialaxis': { 'showticklabels': False, 'showline': False } } } }) print(patient) line_plot_df = df2[df2['patient_id'] == patient] line_plot_df = line_plot_df[ line_plot_df['Task'] < line_plot_df.Task.min() + dt.timedelta(days=35)].reset_index(drop=True) # print(line_plot_df.shape) # print(line_plot_df.head()) fig2 = ff.create_gantt(line_plot_df, index_col='Resource', show_colorbar=True, group_tasks=True, bar_width=0.3) # fig2 = ff.create_gantt(line_plot_df, show_colorbar=True, group_tasks=True) # # fig = go.Figure( # # go.Scatterpolar( # # r = one_day['n_day'], # # theta = one_day['minutes'], # # mode='markers', # # marker = {'size':3.6} # # )) return (fig, fig2)
def plotly_polar_chart(df: pd.DataFrame): """ The input is a dataframe with x and y columns. Create a plotly polar chart with the inputs. DO NOT PLOT IT!! The y input is the same as the line chart, so you need to convert it to an angle. Return the fig only. Feel free to choose between px and go. """ # Plotting the required plotly polar chart fig = px.scatter_polar(df, r="x", theta="y") return fig
def set_graph(data): if not data: raise PreventUpdate data = pd.DataFrame(data) fig = px.scatter_polar(data, r="Alt UT", theta="Az0", range_r=[90, 0], hover_name='Name') return fig
def polar_chart_update(clickData, n): if clickData is not None: point = clickData['points'][0]['pointNumber'] df = streetlight_df[streetlight_df['node_number'] == point] devices = int(df.iloc[0]['time_intensity_norm'] * 50) dist_list = [] angle_list = [] for i in range(0, devices): x = random.randint(1, 50) dist_list.append(x) for i in range(0, devices): x = random.randint(0, 15) dir_list = [ 'N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW' ] angle = dir_list[x] angle_list.append(angle) df_new = pd.DataFrame() df_new['User'] = np.arange(devices) df_new['Distance From Node (m)'] = dist_list df_new['Direction'] = angle_list fig = px.scatter_polar(df_new, r="Distance From Node (m)", theta="Direction", title=f"Devices Around Node: {point}") polar_graph = dcc.Graph(figure=fig) div = dbc.Row( [ dbc.Col(polar_graph, md=8), dbc.Col(dbc.Table.from_dataframe( df_new, striped=True, bordered=True, hover=True), md=4), ], style={"width": "100%"}, # align='center' ) return div
def plot_first_graph(n_clicks, dataset_name, x_column, y_column, graph_type): if n_clicks == None: return go.Figure(), 'Rows Scanned : 0' if dataset_name == 'iris': df = iris_df rows_count = len(iris_df) elif dataset_name == 'video_game': df = video_game_df rows_count = len(video_game_df) elif dataset_name == 'life_expectancy': df = life_expectancy_df rows_count = len(life_expectancy_df) else: df = None categorical_cols = get_text_categorical_columns(df) if x_column in categorical_cols: le = generate_label_encoder(df[x_column]) df = replace_with_label_encoder(df, x_column, le) if y_column in categorical_cols: le = generate_label_encoder(df[y_column]) df = replace_with_label_encoder(df, y_column, le) if graph_type == 'scatter': first_figure = px.scatter(df, x=x_column, y=y_column) elif graph_type == 'histogram': first_figure = px.histogram(df, x=x_column, color=y_column) elif graph_type == 'polar': first_figure = px.scatter_polar(df, r=x_column, theta=y_column) else: first_figure = None final_rows_call = 'Rows Read : ' + str(rows_count) return first_figure, final_rows_call
def graph(): if (str(request.args.get('dorow', None)) == 'true'): # if selecting via rows rbegin = str(request.args.get('rbegin', None)) # grab start and end rows rend = str(request.args.get('rend', None)) else: # else set to default values rbegin = '0' # select from 0 to end of database rend, stmp = db.count() if (str(request.args.get('doangle', None)) == 'true'): # if selecting via angle abegin = str(request.args.get('abegin', None)) # grab start and end angles aend = str(request.args.get('aend', None)) else: # else set to default values abegin = '0' # select from 0 to 360 degrees aend = '360' if (str(request.args.get('dodist', None)) == 'true'): # if selecting via distance dbegin = str(request.args.get('dbegin', None)) # grab start and end distances dend = str(request.args.get('dend', None)) else: # else set to default values dbegin = '0' # select from 0 to 12m dend = '12000' data = pd.DataFrame( db.fetch(rbegin, rend, abegin, aend, dbegin, dend)) # fetch rows and convert to Pandas dataframe frame = px.scatter_polar(data, r=1, theta=0) # plot data as plotly polar spath = os.path.dirname( os.path.realpath('__file__')) # grab current directory path = os.path.join( spath, 'templates/graph.html') # create path to flask templates folder frame.write_html(path) # save plot to templates folder return flask.render_template('graph.html') # return graph
def create_radar_charts(dataframe, feature, sorter): datestr = constants.get_date_str() graphs_results_dir = constants.path_result_dir + datestr + constants.path_graphs_dir out_dir_path = graphs_results_dir + constants.path_radar_graphs_dir if not os.path.exists(out_dir_path): os.makedirs(out_dir_path) #fig = go.Figure() fig = px.scatter_polar(dataframe, r=feature, theta=constants.channel_out_col_title, color=sorter, height=1600, width=1800) #fig = px.line_polar(dataframe, #r=feature, #theta="QCM", #color="Product", #height=1600, width=1600, #) #for product in dataframe['Product'].tolist(): #rows_array = dataframe.loc[dataframe['Product'] == product] #for q in channels_list: #q_rows = rows_array.loc[rows_array['QCM'] == q] #for index, row in q_rows.iterrows(): #print(row) ##fig.show() fig.update_traces(mode="lines+markers", marker=dict(symbol="diamond-open", size=6)) fig.update_layout(polar=dict(radialaxis=dict(visible=True)), showlegend=True, title=feature, font=dict(family="Courier New, monospace", size=32, color="Black"), margin=dict(l=270, r=80, t=80, b=20)) radar_chart_file_name = out_dir_path + '\\' + feature + '_radar_chart.png' fig.write_image(file=radar_chart_file_name, format='png')
x = [] y = [] name = [] phi = 0 i = 0 rows = 4 old = None for row in range(1, rows + 1): print(row) while (phi / (2 * math.pi) // row) < 1: #x.append(phi/(2*math.pi)) x.append(360 * phi / (2 * math.pi)) delta_phi = delta_0 * pow(math.e, phi * 0.0748) y.append(rows - row + 1) phi = phi + delta_phi i += 1 name.append(str(i)) if old: x.append(delta_phi / old) y.append(row - 0.5) name.append("ratio") old = delta_phi #fig = px.scatter(x=x, y=y, log_y=True, hover_name=name) fig = px.scatter_polar(r=y, theta=x, hover_name=name) fig.show()
bins = { '1' : "#f2fffb", '2' : "#bbffeb", '3' : "#98ffe0", '4' : "#79ffd6", '5' : "#6df0c8", '6' : "#69e7c0", '7' : "#59dab2", '8' : "#45d0a5", '9' : "#31c194", '10' : "#2bb489" } test['color'] = test['bins'].map(bins) fig = px.scatter_polar(test) app.layout = html.Div( id="root", children=[ html.Div( id='Header', children=[ html.H4(children="Interactive visualization of PSG data"), html.P( id="description", children="Project for Brainhack 2019 Soraya Lahlou")], style = {'padding' : '40px' , 'backgroundColor' : '#008B8B'}), html.Header(""), dbc.Row(
import plotly.express as px MetsResults = pd.read_csv("mets_2019_results.csv") #Make new column for run differential based on R (runs) and RA (runs against) MetsResults['RDiff'] = MetsResults.R - MetsResults.RA #Consolidate all Ws and Ls into one type of W and L for the W/L column for n in range(0, len(MetsResults)): if MetsResults['W/L'][n] == 'L-wo': MetsResults['W/L'] = MetsResults['W/L'].replace( MetsResults['W/L'][n], 'L') if MetsResults['W/L'][n] == 'W-wo': MetsResults['W/L'] = MetsResults['W/L'].replace( MetsResults['W/L'][n], 'W') fig = px.scatter_polar(MetsResults, r="RDiff", theta="Opp", color="W/L", color_discrete_sequence=px.colors.qualitative.D3, title='Mets 2019 Wins and Losses with Run Differential', labels={ "RDiff": "Run Differential", "Opp": "Opponent" }) fig.update_traces(marker=dict(size=8, line=dict(width=1, color='DarkSlateGrey')), selector=dict(mode='markers')) fig.show()
df = df[['variety', 'common_descriptors']] frequency_table = pd.DataFrame() for i in range(0, len(df.index)): data = df.iloc[i, 1] variety = df.iloc[i, 0] table = pd.DataFrame(data, columns=['Word', 'word_frequency']) table['Variety'] = variety table = table[['Variety', 'Word', 'word_frequency']] frequency_table = frequency_table.append(table, ignore_index=True) # Add columns to calculate percentage of descriptor words frequency_table['total_occ'] = frequency_table.groupby( 'Variety')["word_frequency"].transform('sum') frequency_table['percentage'] = (frequency_table['word_frequency'] / frequency_table['total_occ']) * 100 fig = px.scatter_polar( frequency_table, r="percentage", theta="Word", color="Variety", symbol="Variety", color_discrete_sequence=px.colors.sequential.Plasma[-2::-1], template="seaborn", width=1600, height=1600) fig.show()
orders_by_state = go.Figure(data=go.Choropleth( locations=state['ship-state'], # Two-Letter State Codes z=state['quantity-shipped'].astype(int), # Data to be color-coded locationmode='USA-states', # set of locations match entries in `locations` colorscale='Blues', colorbar_title="Quantity Shipped", )) orders_by_state.update_layout( geo_scope='usa', # limite map scope to USA ) time = px.scatter_polar(orders_by_time, r='quantity-shipped', theta=hour_to_clock.values(), size='quantity-shipped', color='quantity-shipped', color_discrete_sequence=px.colors.sequential.dense) app.layout = html.Div([ dbc.Navbar( [ html.A( # Use row and col to control vertical alignment of logo / brand dbc.Row( dbc.Col( dbc.NavbarBrand("Simple Product Sales Dashboard", className="ml-2")), align="center", no_gutters=True, ),
death_smoothed2[n] = np.interp(t_allday_total, t_allday2[n], death_smoothed2[n]) # create plot for all countries in country_list # for death rate df = pd.DataFrame(list(zip(t_allday_total)), columns =["time (days)"]) for n in range(len(country_list)): df[country_list[n]] = death_smoothed2[n] fig = px.line(df, x='time (days)', y=country_list, title="Death rate") fig.write_html((str("figure_") + str("fig_index") + ".html"), auto_open=True) # for death rate smoothed df = px.data.wind() df = pd.DataFrame(list(zip(t_allday, death_smoothed)), columns =["t_allday", "death_smoothed"]) fig = px.scatter_polar(df, r="death_smoothed", theta="t_allday") fig.write_html((str("figure_") + str("fig_index2") + ".html"), auto_open=True) continents = covid_pd['continentExp'] freq_continents = continents.value_counts() name_continents = freq_continents.index.to_list() print(name_continents) # numbers per continent for n in range(len(name_continents)): covid_pd2 = covid_pd[covid_pd['continentExp']==name_continents[n]] countries = covid_pd2["countriesAndTerritories"] freq_countries = countries.value_counts() name_countries = freq_countries.index.to_list() print()
k2 = sns.boxplot(dataf.Year, df_v.Sales_Gross, palette='Blues', hue_order=[True, False], ax=axes[1, 0]) k3 = sns.heatmap(dataf.corr(), annot=True, cmap='Blues', vmin=-1, vmax=1, yticklabels=False, ax=axes[1, 1]) plt.show() #---------------------------------------------------------------------------------------- #polar chart on gross analysis df = px.data.wind() figu = px.scatter_polar(dataf, r="Total_gross_sales", theta="Gross_Margin", symbol='Sales_Gross', template='plotly_dark', color_discrete_sequence=px.colors.sequential.Blues) plotly.offline.plot(figu, filename='M')
df = px.data.gapminder().query('year == 2007') fig =px.scatter_geo(df,locations ='iso_alpha',hover_name='country',size='pop',projection='orthographic') fig # In[76]: #polar charts # In[82]: df_wind = px.data.wind() px.scatter_polar(df_wind, r= 'frequency',theta = 'direction',color='strength',size='frequency',symbol='strength') # In[84]: df_wind = px.data.wind() px.line_polar(df_wind, r= 'frequency',theta = 'direction',color='strength',line_close=True,template="plotly_dark") # In[85]: #ternary plot
hover_data=tips.columns) # 结果中显示全部数据 # In[34]: wind = px.data.wind() # In[36]: fig = px.scatter_polar( wind, # 数据集 r="frequency", # 半径 theta="direction", # 角度 color="strength", # 颜色 symbol="strength", # 线性闭合 color_discrete_sequence=px.colors.sequential.Plasma_r) # 颜色变化 fig.show() # In[37]: fig = px.line_polar( wind, # 数据集 r="frequency", # 半径 theta="direction", # 角度 color="strength", # 颜色 line_close=True, # 线性闭合
import pandas as pd import plotly.express as px df_full = pd.read_csv("quakes_with_bearings.csv") df_slice = df_full[0:100] fig = px.scatter_polar(df_slice, r='Epic. Dist.(km)', theta="bearing", size='max pga') fig.show() """ fig = px.line(df_slice, x = 'Epic. Dist.(km)', y = ['PGA Vertical (mm/s/s)', 'PGA Horiz_1 (mm/s/s)', 'PGA Horiz_2 (mm/s/s)']) print(df_slice.keys()) fig.show()""" from numpy import arctan2, random, sin, cos, degrees import math """ def compass_bearing(point_1, point_2): lat1 = math.radians(point_1[0]) lat2 = math.radians(point_2[0]) dL = math.radians(point_2[1] - point_1[1]) x = math.sin(dL) * math.cos(lat2) y = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(dL)
fig.update_layout(height=450, hovermode='closest', margin=dict(l=0, r=0, t=0, b=0), mapbox_style="open-street-map", mapbox=dict(bearing=0, center=go.layout.mapbox.Center(lat=-40.2, lon=174.8), pitch=0, zoom=4.5)) pga_dist_scat = px.scatter(x=[0], y=[0]) pga_dist_scat.update_layout(height=450, hovermode='closest', margin=dict(l=0, r=0, t=0, b=0)) polar_plot = px.scatter_polar(r=[0], theta=[0], size=[0]) polar_plot.update_layout(height=450, hovermode='closest', margin=dict(l=0, r=0, t=0, b=0)) app.layout = html.Div([ html.Div([ html.Div([html.H5('Column 1'), dcc.Graph(id="mapbox", figure=fig)], className='six columns'), html.Div([ html.H6(children='Bananatime'), dcc.Graph(id='scat', figure=pga_dist_scat) ], className='six columns') ],
x="Joly", y="Coderre", z="Bergeron", color="winner", line_dash="winner") fig.write_html(os.path.join(dir_name, "line_3d.html")) # #### Polar Coordinates import plotly.express as px wind = px.data.wind() fig = px.scatter_polar( wind, r="frequency", theta="direction", color="strength", symbol="strength", color_discrete_sequence=px.colors.sequential.Plasma[-2::-1], ) fig.write_html(os.path.join(dir_name, "scatter_polar.html")) import plotly.express as px wind = px.data.wind() fig = px.line_polar( wind, r="frequency", theta="direction", color="strength", line_close=True, color_discrete_sequence=px.colors.sequential.Plasma[-2::-1],
import plotly.express as px df = px.data.wind() fig = px.scatter_polar(df, r="frequency", theta="direction") fig.show()