import plotly.plotly as py import plotly.graph_objs as go import numpy as np import pandas as pd npzfile = np.load('prec_raw.npz') #estou enfrentando problemas com memória na proxima linha var = npzfile['var'] latlon = npzfile['latlon'] days = npzfile['days'] #modo não muito eficiente de se tratar dados de dias df_var = pd.DataFrame(var).T #outro jeito de ter a serie de dias do df_days, achei melhor pois tem mais conteudo desse formato na web nday = pd.date_range('1/1/1980', periods=13149, freq='D') df_latlon = pd.DataFrame(latlon) df_days = pd.DataFrame(days) data = [go.Scatter(x=nday, y=df_var[0])] py.iplot(data, filename='Ruberto_var')
from bq_helper import BigQueryHelper import plotly.graph_objs as go from plotly.offline import plot bq_assistant = BigQueryHelper('bigquery-public-data', 'san_francisco') QUERY = """ SELECT * FROM `bigquery-public-data.san_francisco.bikeshare_status` LIMIT 11 """ df = bq_assistant.query_to_pandas(QUERY) print(df.head(10)) print(df.index) trace1 = go.Scatter(x=df.index, y=df.values, mode='lines', name='dd') trace2 = go.Pie(labels=df['time'], values=df['bikes_avaliable']) trace3 = go.Bar(x=df['docks_avaliable'], y=df['bikes_avaliable']) data = [trace1] layout = dict( title='', xaxis=dict(title=''), yaxis=dict(title=''), ) fig = dict(data=[trace1], layout=layout) plot(fig)
import numpy as np import plotly.offline as pyo import plotly.graph_objs as go np.random.seed(42) x = np.random.randint(1, 101, 100) y = np.random.randint(1, 101, 100) data = [ go.Scatter(x=x, y=y, mode='markers', marker=dict(size=12, color='rgb(51,204,153)', symbol='pentagon', line=dict(width=2))) ] layout = go.Layout(title='Hello', xaxis=dict(title='X-axis'), yaxis=dict(title='Y-axis'), hovermode='closest') fig = go.Figure(data=data, layout=layout) pyo.plot(fig, filename='scatter.html')
import plotly.graph_objs as go # trace1 = go.Scatter( # x=[1, 2, 3, 4, 5, # 6, 7, 8, 9, 10, # 11, 12, 13, 14, 15], # y=[10, 20, None, 15, 10, # 5, 15, None, 20, 10, # 10, 15, 25, 20, 10], # name = '<b>No</b> Gaps', # Style name/legend entry with html tags # connectgaps=True # ) trace1 = go.Scatter( y=[ 0.777777777778, 0.8, 0.866666666667, 0.833333333333, 0.791666666667, 0.833333333333, 0.861111111111, 0.836363636364 ], x=[16, 20, 30, 35, 47, 61, 71, 109], name='<b>No</b> Gaps', # Style name/legend entry with html tags connectgaps=True) # trace2 = go.Scatter( # y=[0.823, 0.677,0.75,0.79], # x=[25,30,40,45], # name = 'Gaps' # ) # trace2 = go.Scatter( # x=[1, 2, 3, 4, 5, # 6, 7, 8, 9, 10, # 11, 12, 13, 14, 15], # y=[5, 15, None, 10, 5,
def return_figures(): """Creates four plotly visualizations Args: None Returns: list (dict): list containing the four plotly visualizations """ # first chart plots arable land from 1990 to 2015 in top 10 economies # as a line chart graph_one = [] df = cleandata('data/API_AG.LND.ARBL.HA.PC_DS2_en_csv_v2.csv') df.columns = ['country', 'year', 'hectaresarablelandperperson'] df.sort_values('hectaresarablelandperperson', ascending=False, inplace=True) countrylist = df.country.unique().tolist() for country in countrylist: x_val = df[df['country'] == country].year.tolist() y_val = df[df['country'] == country].hectaresarablelandperperson.tolist() graph_one.append( go.Scatter(x=x_val, y=y_val, mode='lines', name=country)) layout_one = dict( title='Change in Hectares Arable Land <br> per Person 1990 to 2015', xaxis=dict(title='Year', autotick=False, tick0=1990, dtick=25), yaxis=dict(title='Hectares'), ) # second chart plots ararble land for 2015 as a bar chart graph_two = [] df = cleandata('data/API_AG.LND.ARBL.HA.PC_DS2_en_csv_v2.csv') df.columns = ['country', 'year', 'hectaresarablelandperperson'] df.sort_values('hectaresarablelandperperson', ascending=False, inplace=True) df = df[df['year'] == 2015] graph_two.append( go.Bar( x=df.country.tolist(), y=df.hectaresarablelandperperson.tolist(), )) layout_two = dict( title='Hectares Arable Land per Person in 2015', xaxis=dict(title='Country', ), yaxis=dict(title='Hectares per person'), ) # third chart plots percent of population that is rural from 1990 to 2015 graph_three = [] df = cleandata('data/API_SP.RUR.TOTL.ZS_DS2_en_csv_v2_9948275.csv') df.columns = ['country', 'year', 'percentrural'] df.sort_values('percentrural', ascending=False, inplace=True) for country in countrylist: x_val = df[df['country'] == country].year.tolist() y_val = df[df['country'] == country].percentrural.tolist() graph_three.append( go.Scatter(x=x_val, y=y_val, mode='lines', name=country)) layout_three = dict( title='Change in Rural Population <br> (Percent of Total Population)', xaxis=dict(title='Year', autotick=False, tick0=1990, dtick=25), yaxis=dict(title='Percent'), ) # fourth chart shows rural population vs arable land graph_four = [] valuevariables = [str(x) for x in range(1995, 2016)] keepcolumns = [str(x) for x in range(1995, 2016)] keepcolumns.insert(0, 'Country Name') df_one = cleandata('data/API_SP.RUR.TOTL_DS2_en_csv_v2_9914824.csv', keepcolumns, valuevariables) df_two = cleandata('data/API_AG.LND.FRST.K2_DS2_en_csv_v2_9910393.csv', keepcolumns, valuevariables) df_one.columns = ['country', 'year', 'variable'] df_two.columns = ['country', 'year', 'variable'] df = df_one.merge(df_two, on=['country', 'year']) for country in countrylist: x_val = df[df['country'] == country].variable_x.tolist() y_val = df[df['country'] == country].variable_y.tolist() year = df[df['country'] == country].year.tolist() country_label = df[df['country'] == country].country.tolist() text = [] for country, year in zip(country_label, year): text.append(str(country) + ' ' + str(year)) graph_four.append( go.Scatter(x=x_val, y=y_val, mode='markers', text=text, name=country)) layout_four = dict( title= 'Rural Population versus <br> Forested Area (Square Km) 1990-2015', xaxis=dict(title='Rural Population'), yaxis=dict(title='Forest Area (square km)'), ) # TODO: Make a fifth chart from the data in API_SP.RUR.TOTL_DS2_en_csv_v2_9914824.csv # This csv file contains data about the total rural population for various countries over many years # Make a bar chart showing the rural population of these countries ['United States', 'China', 'Japan', 'Germany', 'United Kingdom', 'India', 'France', 'Brazil', 'Italy', 'Canada'] in the year 2015. # HINT: you can use the clean_data() function. You'll need to specify the path to the csv file, and which columns you want to keep. The chart 2 code might help with understanding how to code this. df = cleandata('data/API_SP.RUR.TOTL_DS2_en_csv_v2_9914824.csv') df.columns = ['country', 'year', 'ruralpopulation'] df.sort_values('ruralpopulation', ascending=False, inplace=True) df = df[df['year'] == 2015] # TODO: once the data is clean, make a list called graph_five and append the plotly graph to this list. graph_five = [] graph_five.append( go.Bar( x=df.country.tolist(), y=df.ruralpopulation.tolist(), )) # TODO: fill a layout variable for the fifth visualization layout_five = dict( title='Rural Population per country in 2015', xaxis=dict(title='Country', ), yaxis=dict(title='Rural Population'), ) # append all charts to the figures list figures = [] figures.append(dict(data=graph_one, layout=layout_one)) figures.append(dict(data=graph_two, layout=layout_two)) figures.append(dict(data=graph_three, layout=layout_three)) figures.append(dict(data=graph_four, layout=layout_four)) figures.append(dict(data=graph_five, layout=layout_five)) return figures
import plotly.plotly as py import plotly.graph_objs as go import pandas as pd df = pd.read_csv("~/GOOGLNasdaq2.csv") data = [go.Scatter(x=df.Date, y=df['TradeVol'])] py.iplot(data)
import plotly.plotly as py import plotly.graph_objs as go import requests import numpy as np URL = "http://608dev.net/sandbox/sc/garciag/all_dataHandler.py" r = requests.get(url=URL) data = eval(r.text) temp1 = data[0] temp2 = data[1] temp3 = data[2] N = len(data) random_x = np.linspace(0, 10 * N, N) # Create traces trace0 = go.Scatter(x=random_x, y=temp1, name='Plot 1', mode='lines+markers') trace1 = go.Scatter(x=random_x, y=temp2, name='Plot 2', mode='lines+markers') trace2 = go.Scatter(x=random_x, y=temp3, name='Plot 3', mode='lines+markers') data = [trace0, trace1, trace2] layout = dict(title='Temperature', xaxis=dict(title='Time (min)'), yaxis=dict(title='Degrees Celsius')) fig = go.Figure(data=data, layout=layout) py.plot(fig)
def generate_exercise_charts(timeframe, muscle_options): session, engine = db_connect() df = pd.read_sql(sql=session.query(fitbod).statement, con=engine) engine.dispose() session.close() # Merge 'muscle' into exercise table for mapping df_muscle = pd.read_sql(sql=session.query(fitbod_muscles).statement, con=engine) df = df.merge(df_muscle, how='left', left_on='Exercise', right_on='Exercise') # Filter on selected msucles df = df[df['Muscle'].isin(muscle_options)] # Calculate Volume and aggregate to the daily (workout) level df['Volume'] = df['Reps'].replace(0, 1) * df['Weight'].replace( 0, 1) * df['Duration'].replace(0, 1) # TODO: Change this to sum all volume at workout level instead of taking max of 1 set # df = df.loc[df.groupby(['date_UTC', 'Exercise'])['Volume'].agg(pd.Series.idxmax)].reset_index() df = df.groupby(['date_UTC', 'Exercise'])['Volume'].sum().reset_index() if timeframe == 'ytd': df = df[df['date_UTC'].dt.date >= date(datetime.today().year, 1, 1)] elif timeframe == 'l6w': df = df[df['date_UTC'].dt.date >= (datetime.now().date() - timedelta(days=42))] widgets = [] for exercise in df['Exercise'].unique(): df_temp = df[df['Exercise'] == exercise] try: # Calculate overall start to end % change (1 number) percent_change = ((df_temp['Volume'].tail(1).values[0] - df_temp['Volume'].head(1).values[0]) / \ df_temp['Volume'].head(1).values[0]) * 100 backgroundColor = 'rgb(100,66,66)' if percent_change < 0 else 'rgb(66,100,66)' if percent_change > 0 else 'rgb(66,66,66)' except: backgroundColor = 'rgb(66,66,66)' # Only plot exercise if at least 2 different dates with that exercise if len(df_temp['date_UTC'].unique()) > 1: # Sort by date ascending df_temp = df_temp.sort_values(by=['date_UTC']) # Calculate trend of each data point vs starting point df_temp['% Change'] = df_temp['Volume'].apply( lambda x: ((x - df_temp['Volume'].head(1)) / df_temp['Volume']. head(1)) * 100) tooltip = [ 'Volume:<b>{:.0f} ({}{:.1f}%)'.format(x, '+' if y >= 0 else '', y) for (x, y) in zip(df_temp['Volume'], df_temp['% Change']) ] widgets.append( html.Div( className='two columns maincontainer height-10', style={'backgroundColor': backgroundColor}, children=[ dcc.Graph( id=exercise + '-trend', className='twelve columns nospace', style={'height': '100%'}, config={ 'displayModeBar': False, # 'showLink': True # to edit in studio }, figure={ 'data': [ go.Scatter(x=df_temp['date_UTC'], y=df_temp['% Change'], mode='lines+markers', text=tooltip, hoverinfo='x+text', opacity=0.7, line={'color': teal}), ], 'layout': go.Layout( # title = metricTitle[metric], plot_bgcolor= backgroundColor, # plot bg color paper_bgcolor= backgroundColor, # margin bg color height=150, font=dict( color='rgb(220,220,220)', size=10, ), # hoverlabel={'font': {'size': 10}}, xaxis=dict( showline=True, color='rgb(220,220,220)', showgrid=False, showticklabels=True, tickformat='%b %d', # Specify range to get rid of auto x-axis padding when using scatter markers # range=[df.index.max() - timedelta(days=41), # df.index.max()], # rangeselector=dict( # bgcolor='rgb(66, 66, 66)', # bordercolor='#d4d4d4', # borderwidth=.5, # buttons=buttons, # xanchor='center', # x=.5, # y=1, # ), ), yaxis=dict( showgrid=False, showticklabels=False, gridcolor='rgb(73, 73, 73)', gridwidth=.5, # tickformat='%', ), margin={ 'l': 0, 'b': 25, 't': 20, 'r': 0 }, showlegend=False, annotations=[ go.layout.Annotation( font={'size': 14}, x=df_temp.loc[ df_temp['date_UTC'].idxmax()] ['date_UTC'], y=df_temp.loc[ df_temp['date_UTC'].idxmax()] ['% Change'], xref="x", yref="y", text="{:.1f}%".format(df_temp.loc[ df_temp['date_UTC'].idxmax( )]['% Change']), showarrow=True, arrowhead=0, arrowcolor=white, ax=5, ay=-20) ], hovermode='x', autosize=True, title=exercise) }) ])) # Set up each div of 6 graphs to be placed in num_divs = math.ceil(len(widgets) / 6) div_layout = [] for i in range(0, num_divs): children = [] for widget in widgets[:6]: children.append(widget) widgets.remove(widget) div_layout.append( html.Div(className='twelve columns', children=children)) div_layout.append( html.Div(className='twelve columns', style={ 'backgroundColor': 'rgb(66, 66, 66)', 'paddingBottom': '1vh' })) return div_layout
import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go import pandas as pd # Launch the application: app = dash.Dash() # Create a DataFrame from the .csv file: df = pd.read_csv('C:\\Users\\wallj\\DS_Projects\\udemy_Plotly_Dash\\Plotly-Dashboards-with-Dash\\Data\\OldFaithful.csv') # Create a Dash layout that contains a Graph component: app.layout = html.Div([dcc.Graph(id='old_faithful', figure={'data':[go.Scatter(x=df['X'], y=df['Y'], mode='markers')] layouit})]) if __name__ == '__main__': app.run_server()
def create_line_graphics(x_axe, y_lists, names, graphic_name="default"): data = [] for i in range(len(y_lists)): trace = go.Scatter(x=x_axe, y=y_lists[i], name=names[i]) data.append(trace) print(py.iplot(data, filename=graphic_name))
def plot_freq_comparison(parameters): freqA = parameters['ieeg']['ecog_compare']['frequency_bands'][ parameters['plot']['compare']['freqA']] freqB = parameters['ieeg']['ecog_compare']['frequency_bands'][ parameters['plot']['compare']['freqB']] actA = read_tsv(get_path(parameters, 'summary_tsv', frequency_band=freqA)) actB = read_tsv(get_path(parameters, 'summary_tsv', frequency_band=freqB)) max_r = max(r_[actA['r2_at_peak'], actB['r2_at_peak']]) result = ttest_rel(actA['r2_at_peak'], actB['r2_at_peak']) traces = [ go.Scatter( x=actA['r2_at_peak'], y=actB['r2_at_peak'], text=actA['subject'], mode='markers', marker=dict(color='black', ), ) ] figs = [] fig = go.Figure( data=traces, layout=go.Layout( height=500, width=500, title=dict( text= f'R<sup>2</sub> values (paired t-test, <i>p</i> = {result.pvalue:0.03f})' ), xaxis=dict( title=dict(text=axis_label(freqA), ), tick0=0, dtick=0.1, range=[0, max_r + 0.1], ), yaxis=dict( title=dict(text=axis_label(freqB), ), tick0=0, dtick=0.1, range=[0, max_r + 0.1], ), shapes=[ dict(type='line', layer='below', x0=0, x1=max_r + 0.1, y0=0, y1=max_r + 0.1, line=dict(color='gray', )) ])) figs.append(fig) for param in ('size_at_peak', 'size_at_concave'): fig = _plot_compare_size(actA, actB, param, parameters, freqA, freqB) figs.append(fig) param = 'slope_at_peak' min_r = min(r_[actA[param], actB[param]]) max_r = max(r_[actA[param], actB[param]]) diff_act = mean(actA[param] - actB[param]) result = ttest_rel(actA[param], actB[param]) regr = linregress(actA['slope_at_peak'], actB['slope_at_peak']) traces = [ go.Scatter( x=actA[param], y=actB[param], text=actA['subject'], mode='markers', marker=dict(color='black', ), ) ] fig = go.Figure( data=traces, layout=go.Layout( height=500, width=500, title=dict( text= f'Difference [{freqA[0]}-{freqA[1]}] Hz - [{freqB[0]}-{freqB[1]}] Hz = {diff_act:0.2f}<br />paired t-test, <i>p</i> = {result.pvalue:0.03f}<br />regression slope = {regr.slope:0.3f} <i>p</i> = {regr.pvalue:0.03f}' ), xaxis=dict( title=dict(text=axis_label(freqA), ), tick0=0, dtick=0.2, range=[min_r - 0.1, max_r + 0.1], ), yaxis=dict( title=dict(text=axis_label(freqB), ), tick0=0, dtick=0.2, range=[min_r - 0.1, max_r + 0.1], scaleanchor="x", scaleratio=1, ), shapes=[ dict(type='line', layer='below', x1=-min_r - 0.1, x0=-max_r - 0.1, y1=min_r + 0.1, y0=max_r + 0.1, line=dict(color='gray', )), dict(type='line', layer='below', x0=0, x1=1, y0=0, y1=0, xref='paper', line=dict( width=2, color='gray', )), dict(type='line', layer='below', x0=0, x1=0, y0=0, y1=1, yref='paper', line=dict( width=2, color='gray', )), ])) figs.append(fig) return figs
import plotly.offline as pyo import plotly.graph_objs as go import pandas as pd df = pd.read_csv('Data/mpg.csv') data = [go.Scatter( # start with a normal scatter plot x=df['horsepower'], y=df['mpg'], text=df['name'], mode='markers', marker=dict(size=1.5*df['cylinders']) # set the marker size )] layout = go.Layout( title='Vehicle mpg vs. horsepower', xaxis = dict(title = 'horsepower'), # x-axis label yaxis = dict(title = 'mpg'), # y-axis label hovermode='closest' ) fig = go.Figure(data=data, layout=layout) pyo.plot(fig, filename='bubble1.html')
#scatter plot scatter_sub = pd.read_csv("/data/submissions_plot_06032019.csv") scatter_sub['y'] = scatter_sub['y'].astype(str) app.layout = html.Div([ dcc.Graph( id='scatter_chart', figure={ 'data': [ go.Scatter( x=scatter_sub[scatter_sub['y'] == i]['Dimension1'], y=scatter_sub[scatter_sub['y'] == i]['Dimension2'], text=scatter_sub[scatter_sub['y'] == i]['SubmissionTitle'], mode='markers', opacity=0.8, marker={ 'size': 4, 'line': { 'width': 0.5, 'color': 'white' } }, name=i) for i in scatter_sub.y.unique() ], 'layout': go.Layout(xaxis={'title': 'Dimension 1'}, yaxis={'title': 'Dimension 2'}, margin={ 'l': 40, 'b': 40, 't': 10, 'r': 10
def sim_line_graph_measure_surveys(df1, course_code, measures=[ 'subject_content', 'lecturer_effectiveness', 'course_satisfaction' ], start_year=2017, end_year=2019, semester=None, width=520, height=300): f_df = df1.loc[df1['course_code'] == course_code] # all traces for plotly traces = [] xlabels = [] for year in range(int(start_year), int(end_year) + 1): if semester == 1 or semester == 2: xlabels.append('{}<br> S{}'.format(year, semester)) semesters = [semester] else: xlabels.append('{}<br> S1'.format(year)) xlabels.append('{}<br> S2'.format(year)) semesters = [1, 2] no_terms = len(xlabels) x = [i - 0.5 for i in range(1, no_terms + 1)] label_check = 0 graph_title = '' for measure in measures: graph_title += '{}, '.format(get_name(measure)) for staff_type in ['Local', 'RMIT']: data_label = [] y = [] label_check += 1 for year in range(int(start_year), int(end_year) + 1): for sem in semesters: try: val = pd.to_numeric( f_df.loc[(f_df['year'] == int(year)) & (f_df['semester'] == int(sem)) & (f_df['staff_type'] == staff_type)].iloc[0][measure]) except: val = None y.append(val) trace = go.Scatter(x=x, y=y, name='{}'.format(staff_type), text=data_label, line=go.scatter.Line(width=2, color=get_colour(measure), dash=get_dash(staff_type)), marker=go.scatter.Marker( color=get_colour(measure), size=8, symbol=get_symbol(staff_type)), connectgaps=False, mode='lines+markers', showlegend=True, textposition='top center') traces.append(trace) graph_title = graph_title[:-2] + ' ' title = 'SIM {} {}'.format(graph_title[:-1], course_code) fig = go.Figure(data=traces, layout=go.Layout( title=title, showlegend=True, xaxis=dict( range=[0, no_terms], tickvals=x, showgrid=False, ticktext=xlabels, ticks='outside', tick0=1, dtick=1, ticklen=5, zeroline=True, zerolinewidth=2, ), yaxis=dict( title='Mean value', range=[3.45, 4.55], tickvals=[ 3.5, 3.6, 3.7, 3.8, 3.9, 4.0, 4.1, 4.2, 4.3, 4.4, 4.5 ], ticklen=5, zeroline=True, zerolinewidth=2, ), width=width, height=height, hovermode='closest', margin=dict(b=40, l=50, r=5, t=40), hidesources=True, )) return fig
app = dash.Dash(__name__, external_stylesheets=external_stylesheets) marka_ido_df = pd.read_csv(str(Path("marka_ido.csv")) app.layout = html.Div([ dcc.Graph( id='life-exp-vs-gdp', figure={ 'data': [ go.Scatter( x=marka_ido_df[marka_ido_df['MARKA'] == m]['eladasig_nap'], y=marka_ido_df[marka_ido_df['MARKA'] == m]['piacon_nap'], text= m, mode='markers', opacity=0.7, marker={ 'size': 10, 'line': {'width': 0.5, 'color': 'white'} }, name=m ) for m in marka_ido_df.MARKA ], 'layout': go.Layout( xaxis={'title': 'Az eladásig eltelt átlagos idő (nap)'}, yaxis={'title': 'A jelenleg elérhető autók átlagos piacon töltött ideje'}, #margin={'l': 40, 'b': 40, 't': 10, 'r': 10}, legend={'x': 0, 'y': 1}, hovermode='closest' ) }, style = {'height': 800}
def update_graph(jsonified_cleaned_data): # more generally, this line would be # json.loads(jsonified_cleaned_data) df_live_db = pd.read_json(jsonified_cleaned_data, orient='split') # plot each # set a common x axis label! traces = [] # traces.append(go.Scatter( # x=df_live_db['date'], # y=df_live_db['dose']/10, # text='dose [0.1 muSv/hr]', # # mode='markers', # opacity=0.7, # # marker={ # # 'size': 15, # # 'line': {'width': 0.5, 'color': 'white'} # # }, # name='dose [0.1 muSv/hr]' # )) # HV voltage traces.append(go.Scatter( x=df_live_db['date'], y=df_live_db['HV_voltage'], text='HV_voltage [x -1kV]', line=go.scatter.Line( color='red', width=1.5 ), # mode='markers', opacity=0.7, # marker={ # 'size': 15, # 'line': {'width': 0.5, 'color': 'white'} # }, name='HV_voltage [-kV]' )) # HV current traces.append(go.Scatter( x=df_live_db['date'], y=df_live_db['HV_current']*100, text='HV_current [x -100mA]', line=go.scatter.Line( color='orange', width=1.5 ), # mode='markers', opacity=0.7, # marker={ # 'size': 15, # 'line': {'width': 0.5, 'color': 'white'} # }, name='HV_current [-100 mA]' )) return { 'data': traces, 'layout': go.Layout( xaxis={'type': 'date', 'title': 'Time'}, yaxis={'title': ' ', 'range': [0, 150]}, margin={'l': 40, 'b': 40, 't': 10, 'r': 10}, legend={'x': 0, 'y': 1}, hovermode='closest' ) }
def trace_getter(date,revenue): trace = go.Scatter( x = date, y = revenue, name = 'EZ_PZ_RPG_3D') return trace
def update_figure_today(n_clicks): t = int(float(hours_to_plot_today) * 3600.0) df_dose = retrieveLiveData(t) # retrieve the past 2 hrs # plot each # set a common x axis label! traces = [] # DOSE # print(df_dose.head()) traces.append(go.Scatter( x=df_dose['date'], y=df_dose['dose']/10, text='dose [0.1 muSv/hr]', # mode='markers', opacity=0.7, # marker={ # 'size': 15, # 'line': {'width': 0.5, 'color': 'white'} # }, name='dose [0.1 muSv/hr]' )) # HV voltage traces.append(go.Scatter( x=df_dose['date'], y=df_dose['HV_voltage'], text='HV_voltage [-kV]', line=go.scatter.Line( color='red', width=1.5 ), # mode='markers', opacity=0.7, # marker={ # 'size': 15, # 'line': {'width': 0.5, 'color': 'white'} # }, name='HV_voltage [-kV]' )) # HV current traces.append(go.Scatter( x=df_dose['date'], y=df_dose['HV_current']*100, text='HV_current [-100 mA]', line=go.scatter.Line( color='orange', width=1.5 ), # mode='markers', opacity=0.7, # marker={ # 'size': 15, # 'line': {'width': 0.5, 'color': 'white'} # }, name='HV_current [-100 mA]' )) return { 'data': traces, 'layout': go.Layout( xaxis={'type': 'date', 'title': 'Time'}, yaxis={'title': 'Y', 'range': [0, 150]}, margin={'l': 40, 'b': 40, 't': 10, 'r': 10}, legend={'x': 0, 'y': 1}, hovermode='closest' ) }
#C:\Python34\Lib\site-packages\;all iofo from hereh ttps://plot.ly/python/line-charts/ import plotly.plotly as py import plotly.graph_objs as go import plotly month = [i for i in range(1,12*3+1)] uSergei= go.Scatter( x = month, y=[None, None ,None , None, 11000, 14100, 16109, 11230, 4000, 10700, 17626, 43245, 17200, 29177, 24377, 26406, 15000, 21153, 20805, 17905, 11962, 18614, 7904, 24662, 21000, 34442, 34420,20743,13792,17685,12050], mode = 'lines+markers', # 'markers', 'lines' name = 'Sergei', line=dict(shape='spline', # spline options include 'linear', 'vh', 'hv', 'vhv', 'hvh' #color = ('rgb(205, 12, 24)'), #wconnectgaps=True, width = 1, dash = 'dash') # dash options include 'dash', 'dot', and 'dashdot'v ) uOleg = go.Scatter( x = month, y = [28400, 73070, 47690, 43760, 31900, 33410, 31267, 30548, 30519, 31182, 59133, 36265 ,33726 ,21248 ,28328 ,22115 ,31000 ,24876 ,20885 ,39335 ,36847 ,48424 ,31908 ,16931 ,26947 ,35910 ,34144, 27062,34362,30672,35838], mode = 'lines+markers', name = 'Oleg', line=dict(shape='spline'), ) uDima = go.Scatter( x = month,
def _plot_history(self): # type: () -> None """Plot the results of the last B2k iteration in the browser.""" traces_des_vars = [] des_var_names = sorted(self.OPT_DV_VALUES.keys()) legend_entries = [x.split('/')[-1] for x in des_var_names] for var_name, legend_name in zip(des_var_names, legend_entries): ref0s = self.REF0_VALUES[var_name] refs = self.REF_VALUES[var_name] val_opt = [ float(unscale_value(val, ref0s[k], refs[k])) for k, val in enumerate(self.OPT_DV_VALUES[var_name]) ] val_lb = [ float(unscale_value(val[0], ref0s[k], refs[k])) for k, val in enumerate(self.LOCAL_BOUNDS[var_name]) ] val_ub = [ float(unscale_value(val[1], ref0s[k], refs[k])) for k, val in enumerate(self.LOCAL_BOUNDS[var_name]) ] error_y = [] error_y_minus = [] for j in range(len(self.OPT_DV_VALUES[var_name])): for l in range(len(val_opt)): if val_ub[l] > val_opt[l]: error_y.append(abs(val_ub[l] - val_opt[l])) else: error_y.append(0.) if val_lb[l] < val_opt[l]: error_y_minus.append(abs(val_lb[l] - val_opt[l])) else: error_y_minus.append(0.) trace = go.Scatter(x=list(range(len(val_opt))), y=val_opt, mode='markers', name=legend_name, error_y=dict(type='data', symmetric=False, array=error_y, arrayminus=error_y_minus), marker=dict(size=12)) traces_des_vars.append(trace) layout_des_vars = go.Layout( title='Design variables of top-level system optimization', showlegend=True, xaxis=dict(title='iteration'), yaxis=dict(title='value')) fig_des_vars = go.Figure(data=traces_des_vars, layout=layout_des_vars) output_folder = self.system_optimizer_prob.model.data_folder output_case_str = self.system_optimizer_prob.output_case_string plotly.offline.plot( fig_des_vars, filename=os.path.join( output_folder, 'b2k_des_vars_{}.html'.format(output_case_str)), auto_open=False) # Plot constraints create_plotly_plot(self.OPT_CON_VALUES, 'Constraints of top-level system optimization', 'b2k_cons_{}.html'.format(output_case_str), folder=output_folder) # Plot objective value(s) create_plotly_plot(self.OPT_OBJ_VALUES, 'Objective(s) of top-level system optimization', 'b2k_obj_{}.html'.format(output_case_str), folder=output_folder)
#建立散佈圖 app.layout = html.Div([ html.H2(children='身高體重'), dcc.Graph( id='gapminder', figure={ 'data': [ go.Scatter( x=df['height'], y=df['fans'], text=df['name'], mode='markers', opacity=0.7, marker={ 'size': df['size'], 'line': {'width': 0.5, 'color': 'white'}, 'sizeref': sizeref, 'symbol': 'circle', 'sizemode': 'area' }, name="tt" ) ], 'layout': go.Layout( xaxis={'type': 'log', 'title': '身高'}, yaxis={'title': '體重'}, margin={'l': 40, 'b': 40, 't': 10, 'r': 10}, legend={'x': 0, 'y': 1}, hovermode='closest' )
# For ease of use, we will put our data in a pandas dataframe. df = pd.DataFrame.from_records(data, columns=cols) df = df.drop(columns=['GRID_TYPE']) colors = { 'background': '#111111', 'text': '#7FDBFF' } # Create the scatters for the missed shots and the made shots. missed_shot_trace = go.Scatter( x = df[df['EVENT_TYPE'] == 'Missed Shot']['LOC_X'], y = df[df['EVENT_TYPE'] == 'Missed Shot']['LOC_Y'], mode = 'markers', name = 'Miss', marker = {'color':'blue', 'size':5} ) made_shot_trace = go.Scatter( x = df[df['EVENT_TYPE'] == 'Made Shot']['LOC_X'], y = df[df['EVENT_TYPE'] == 'Made Shot']['LOC_Y'], mode = 'markers', name = 'Make', marker = {'color':'red', 'size':5} ) # Organized these scatters and combine them together. data = [missed_shot_trace, made_shot_trace]
def variant_diffs_scatter_plot(data, labels, features, output_path, filter_features=None, labels_sort_fn=ordered_variants_and_indices, nth_percentile=None, hg_reference_version=None, threshold_line=None, auto_open=False): """ Displays each variant's max probability difference across features as a point in a scatter plot. The points in the scatter plot are ordered by the variant chromosome and position by default. Variants can be sorted differently by passing in a new `labels_sort_fn`. Parameters ---------- data : np.ndarray Absolute difference scores for variants across all features that a model predicts. This is the first value in the tuple returned by `load_variant_abs_diff_scores`. labels : list(tuple(str)) A list of variant labels. This is the second value in the tuple returned by `load_variant_abs_diff_scores`. features : list(str) A list of the features the model predicts. This is the third value in the tuple returned by `load_variant_abs_diff_scores`. output_path : str Path to output file. Must have '.html' extension. filter_features : types.FunctionType or None, optional Default is None. A function that takes in a `list(str)` of features and returns the `list(int)` of feature indices over which we would compute the max(probability difference) for each variant. For example, a user may only want to visualize the max probability difference for TF binding features. If `None`, uses all the features. labels_sort_fn : types.FunctionType, optional Default is `ordered_variants_and_indices`. A function that takes in a `list(tuple(str))` of labels corresponding to the rows in `data` and returns a `tuple(list(tuple), list(int))`, where the first value is the ordered list of variant labels and the second value is the ordered list of indices for those variant labels. By default, variants are sorted by chromosome and position. nth_percentile : int [0, 100] or None, optional Default is None. If `nth_percentile` is not None, only displays the variants with a max absolute difference score within the `nth_percentile` of scores. hg_reference_version : str {"hg19", "hg38"} or None, optional Default is None. On hover, we can display the gene(s) closest to each variant if `hg_reference_version` is not None, where closest can be a variant within a gene interval (where genes and their coordinates are taken from level 1 & 2 protein-coding genes in gencode v28) or near a gene. In the future, we will allow users to specify their own genome file so that this information can be annotated to variants from other organisms, other genome versions, etc. threshold_line : float or None, optional Default is None. If `threshold_line` is not None, draws a horizontal line at the specified threshold. Helps focus the visual on variants above a certain threshold. auto_open : bool, optional Default is False. If `auto_open`, will automatically open a web browser that displays the plotted HTML file. Returns ------- plotly.graph_objs.graph_objs.Figure The generated Plotly figure. """ labels_ordered, label_indices = labels_sort_fn(labels) variant_closest_genes = None if hg_reference_version is not None: variant_closest_genes = _variants_closest_protein_coding_gene( labels_ordered, version=hg_reference_version) ordered_data = data[label_indices, :] feature_indices = None if filter_features is not None: feature_indices = filter_features(features) ordered_data = data[:, feature_indices] variants_max_diff = np.amax(ordered_data, axis=1) display_labels = None if nth_percentile: p = np.percentile(variants_max_diff, nth_percentile) keep = np.where(variants_max_diff >= p)[0] print("{0} variants with max abs diff score above {1} are in the " "{2}th percentile.".format(len(keep), p, nth_percentile)) variants_max_diff = variants_max_diff[keep] display_labels = [] for i, l in enumerate(labels_ordered): if i not in keep: continue display_labels.append(l) else: display_labels = labels_ordered if variant_closest_genes: text_labels = [ _label_tuple_to_text(l, d, g) for l, d, g in zip( display_labels, variants_max_diff, variant_closest_genes) ] else: text_labels = [ _label_tuple_to_text(l, d) for l, d in zip(display_labels, variants_max_diff) ] label_x = [' '.join([l[0], str(l[1])]) for l in display_labels] data = [ go.Scatter(x=label_x, y=variants_max_diff, mode='markers', marker=dict(color="#39CCCC", line=dict(width=1)), text=text_labels, hoverinfo="text") ] go_layout = { "title": "Max probability difference scores", "hovermode": "closest", "hoverlabel": { "font": { "size": 16 } }, "xaxis": { "title": "Genome coordinates", "showticklabels": True, "tickangle": 35, "titlefont": { "family": "Arial, sans-serif", "size": 16 }, "nticks": 25, "tickmode": "auto", "automargin": True }, "yaxis": { "title": "Absolute difference", "titlefont": { "family": "Arial, sans-serif", "size": 16 } } } if isinstance(threshold_line, float): layout = go.Layout(**go_layout, shapes=[{ "type": "line", "x0": label_x[0], "y0": threshold_line, "x1": label_x[-1], "y1": threshold_line, "line": { "color": "rgba(255, 99, 71, 1)", "width": 2 } }]) else: layout = go.Layout(**go_layout) fig = go.Figure(data=data, layout=layout) path, filename = os.path.split(output_path) os.makedirs(path, exist_ok=True) plot(fig, filename=output_path, auto_open=auto_open) return fig
def make_vix_line_plot(hidden): if hidden == 'loaded': trace1 = go.Scatter( x=vix_df.index, y=vix_df.VIX, mode='lines+markers', name="VIX", hoverinfo='y', line=dict( shape='linear' ) ) trace2 = go.Scatter( x=vix_df.index, y=vix_df.F1, mode='lines+markers', name="F1", hoverinfo='y', line=dict( shape='linear' ) ) trace3 = go.Scatter( x=vix_df.index, y=vix_df.F2, mode='lines+markers', name="F2", hoverinfo='y', line=dict( shape='linear' ) ) trace4 = go.Scatter( x=vix_df.index, y=vix_df.Contango, mode='lines+markers', name="Contango", hoverinfo='y', yaxis='y2', line=dict( shape='linear' ) ) layout = dict( yaxis=dict( title='VIX' ), yaxis2=dict( title='Contango', overlaying='y', side='right', showgrid=False, zeroline=False, showline=False, ticks='' ), legend=dict( y=1, font=dict( size=16 ) ) ) data = [trace1, trace2, trace3, trace4] figure = dict(data=data, layout=layout) return figure
dt_user['Segment'] = 'Low-Value' dt_user.loc[dt_user['OverallScore'] > 2, 'Segment'] = 'Mid-Value' dt_user.loc[dt_user['OverallScore'] > 4, 'Segment'] = 'High-Value' # In[22]: dt_graph = dt_user.query("Revenue < 50000 and Frequency < 2000") plot_data = [ go.Scatter( x = dt_graph.query("Segment == 'Low-Value'")['Frequency'], y = dt_graph.query("Segment == 'Low-Value'")['Revenue'], mode = 'markers', name = "Low", marker= dict(size= 7, line= dict(width=1), color= 'blue', opacity= 0.8 ) ), go.Scatter( x=dt_graph.query("Segment == 'Mid-Value'")['Frequency'], y=dt_graph.query("Segment == 'Mid-Value'")['Revenue'], mode='markers', name='Mid', marker= dict(size= 9, line= dict(width=1), color= 'green', opacity= 0.5 )
patientcard JOIN doctors ON patientcard.doctor_license = doctors.lisence JOIN patient ON patient.surname=patientcard.patient_surname GROUP BY patientcard.appointment ORDER BY patientcard.appointment """) dates = [] patients = [] for row in cursor: print("Date ", row[0], " count: ", row[1]) dates += [row[0]] patients += [row[1]] date_patients = go.Scatter(x=dates, y=patients, mode='lines+markers') data = [date_patients] date_patient = py.plot(data, filename='Appointments by date') """--------CREATE DASHBOARD------------------ """ my_board = dashboard.Dashboard() doctors_patient_count_id = fileId_from_url(doctors_patient_count) doctor_patient_percent_id = fileId_from_url(doctor_patient_percent) date_patient_id = fileId_from_url(date_patient) box_1 = { 'type': 'box', 'boxType': 'plot', 'fileId': doctors_patient_count_id, 'title': 'Doctors and count of his patients'
def plot(self, instrument=None, engine='plotly', notebook=False): if engine == 'plotly': if type(instrument) == str: df = pd.DataFrame(self.bar_dict[instrument]) df.set_index('date', inplace=True) df.index = pd.DatetimeIndex(df.index) p_symbol = go.Scatter(x=df.index, y=df.close, xaxis='x3', yaxis='y3', name=instrument) # p_volume = go.Bar(x=df.index,y=df['volume'], # xaxis='x3',yaxis='y5',opacity=0.5,name='volume') self.data.append(p_symbol) # self.data.append(p_volume) if type(instrument) == list: for i in instrument: df = pd.DataFrame(self.bar_dict[i]) df.set_index('date', inplace=True) df.index = pd.DatetimeIndex(df.index) p_symbol = go.Scatter(x=df.index, y=df.close, xaxis='x3', yaxis='y3', name=i) p_volume = go.Bar(x=df.index, y=df['volume'], xaxis='x3', yaxis='y5', opacity=0.5, name=i + 'volume') self.data.append(p_symbol) self.data.append(p_volume) for i in self.positions_df: p_position = go.Scatter(x=self.positions_df.index, y=self.positions_df[i], xaxis='x2', yaxis='y2', name=i) p_total = go.Scatter(x=self.total_df.index, y=self.total_df.total, xaxis='x6', yaxis='y6', name='total') p_cash = go.Scatter(x=self.cash_df.index, y=self.cash_df.cash, xaxis='x6', yaxis='y6', name='cash') p_re_profit = go.Scatter(x=self.re_profit_df.index, y=self.re_profit_df.re_profit, xaxis='x4', yaxis='y4', name='realized_profit') p_unre_profit = go.Scatter(x=self.unre_profit_df.index, y=self.unre_profit_df.unre_profit, xaxis='x4', yaxis='y4', name='unrealized_profit') p_commission = go.Scatter(x=self.commission_df.index, y=self.commission_df.commission, xaxis='x4', yaxis='y4', name='commission') self.data.append(p_position) self.data.append(p_total) self.data.append(p_cash) self.data.append(p_unre_profit) self.data.append(p_re_profit) self.data.append(p_commission) layout = go.Layout(xaxis2=dict(domain=[0, 1], anchor='y2', scaleanchor='x2'), xaxis3=dict(domain=[0, 1], anchor='y3', scaleanchor='x2'), xaxis4=dict(domain=[0, 1], anchor='y4', scaleanchor='x2'), xaxis6=dict(domain=[0, 1], anchor='y6', scaleanchor='x2'), yaxis2=dict(domain=[0, 0.15], scaleanchor='x2'), yaxis3=dict(domain=[0.15, 0.65], scaleanchor='x2'), yaxis4=dict(domain=[0.65, 0.85], scaleanchor='x2'), yaxis5=dict( domain=[0.15, 0.65], side='right', range=[0, 10000000], overlaying='y3', tickvals=[0, 1000000, 2000000, 2500000], showgrid=False, scaleanchor='x2'), yaxis6=dict(domain=[0.85, 1], scaleanchor='x2')) fig = go.Figure(data=self.data, layout=layout) if notebook: import plotly plotly.offline.init_notebook_mode() py.iplot(fig, filename='OnePy_plot.html', validate=False) else: py.plot(fig, filename='OnePy_plot.html', validate=False)
data=pd.read_csv(r"C:\Users\eceti\Desktop\phyton\DataAi\Data Visualization\Mall_Customers.csv", encoding="cp1252") data.info() data.head() # prepare data frame Annual_Income=data.iloc[:,3] Spending_Score=data.iloc[:,4] Age=data.iloc[:,2] Gender=data.iloc[:,1] Index=data.iloc[:,0] trace1 = go.Scatter( x=Spending_Score, y=Gender, name = "research" ) trace2 = go.Scatter( x=Spending_Score, y=Age, xaxis='x2', yaxis='y2', name = "citations" ) trace3 = go.Scatter( x=Spending_Score, y=Annual_Income, xaxis='x3', yaxis='y3', name = "income"
import pandas as pd import plotly.offline as pyo import plotly.graph_objs as go # Load CSV file from Datasets folder df = pd.read_csv('../Datasets/Weather2014-15.csv') # Preparing data data = [ go.Scatter(x=df['month'], y=df['actual_max_temp'], mode='lines', name='actual max temp') ] # Preparing layout layout = go.Layout(title='Actual Maximum Temperature ', xaxis_title="Month", yaxis_title="Actual Max Temp") # Plot the figure and saving in a html file fig = go.Figure(data=data, layout=layout) pyo.plot(fig, filename='linechartWeather.html')
def gen_ohlcv(interval: int) -> go.Figure: """Generate OHLCV Chart for BTCUSD with predicted price overlay. Args: interval: update the graph based on an interval """ # hack to wrap interval around available data. OOS starts at 1500, # df has a total of 2274 rows after processing to wrap around # 2274-1500 ~ 750. Reset prediction data to empty df. interval = interval % 750 print("interva is {}...".format(interval)) # read data from source df = get_ohlcv_data(interval - 100, interval) df["log_ret"] = np.log(df.Close) - np.log(df.Close.shift(1)) print("\ndata df loaded, starting prediction...\n") # online training and forecast. model = ARIMA( df.tail(60)["log_ret"], order=(3, 1, 0), freq="D", ).fit(disp=0) pred = model.forecast()[0] print("\nprediction ended, writing to output df...") # save forecast to output dataframe. should be dB irl. next_dt = df.tail(1).index[0] + pd.Timedelta("1 day") config.df_pred.loc[next_dt] = [ pred[0], (np.exp(pred) * df.tail(1).Close.values)[0], ] print("\nnext datetime is {}...".format(next_dt)) # get index location of period. loc = config.df_pred.index.get_loc(next_dt) + 1 print("\nloc is {}...".format(loc)) # slices for the past N periods perdiction for plotting df_pred_plot = config.df_pred.iloc[slice(max(0, loc - 30), min(loc, len(df)))].sort_index() print("\n set pred df for plotting...\n", df_pred_plot) # plotting ohlc candlestick trace_ohlc = go.Candlestick( x=df.tail(50).index, open=df["Open"].tail(50), close=df["Close"].tail(50), high=df["High"].tail(50), low=df["Low"].tail(50), opacity=0.5, hoverinfo="skip", name="BTCUSD", ) # plotting prediction line trace_line = go.Scatter( x=df_pred_plot.index, y=df_pred_plot.pred_Close, line_color="yellow", mode="lines+markers", name="Predicted Close", ) layout = go.Layout( plot_bgcolor=config.app_color["graph_bg"], paper_bgcolor=config.app_color["graph_bg"], font={"color": "#fff"}, height=700, xaxis={ "showline": False, "showgrid": False, "zeroline": False }, yaxis={ "showgrid": True, "showline": True, "fixedrange": True, "zeroline": True, "gridcolor": config.app_color["graph_line"], "title": "Price (USD$)", }, ) return go.Figure(data=[trace_ohlc, trace_line], layout=layout)