Beispiel #1
0
def plot_koalas(data: Union["ks.DataFrame", "ks.Series"], kind: str, **kwargs):
    import plotly

    # Koalas specific plots
    if kind == "pie":
        return plot_pie(data, **kwargs)
    if kind == "hist":
        return plot_histogram(data, **kwargs)
    if kind == "box":
        return plot_box(data, **kwargs)

    # Other plots.
    return plotly.plot(KoalasPlotAccessor.pandas_plot_data_map[kind](data),
                       kind, **kwargs)
Beispiel #2
0
def plot_pandas_on_spark(data: Union["ps.DataFrame", "ps.Series"], kind: str, **kwargs):
    import plotly

    # pandas-on-Spark specific plots
    if kind == "pie":
        return plot_pie(data, **kwargs)
    if kind == "hist":
        return plot_histogram(data, **kwargs)
    if kind == "box":
        return plot_box(data, **kwargs)
    if kind == "kde" or kind == "density":
        return plot_kde(data, **kwargs)

    # Other plots.
    return plotly.plot(PandasOnSparkPlotAccessor.pandas_plot_data_map[kind](data), kind, **kwargs)
Beispiel #3
0
else:
    dates = [q[0] for q in quotes]
    y = [q[1] for q in quotes]
    for date in dates:
        x.append(datetime.fromordinal(int(date))\
                .strftime('%Y-%m-%d')) # Plotly timestamp format
    ma = moving_average(y, 10)

# vvv clip first and last points of convolution
mov_avg = go.Scatter( x=x[5:-4], y=ma[5:-4], \
                  line=dict(width=2,color='red',opacity=0.5), name='Moving average' )
data = [xy_data, mov_avg]

py.iplot(data, filename='apple stock moving average')

first_plot_url = py.plot(data, filename='apple stock moving average', auto_open=False,)
print first_plot_url

tickers = ['AAPL', 'GE', 'IBM', 'KO', 'MSFT', 'PEP']
prices = []
for ticker in tickers:
    quotes = quotes_historical_yahoo(ticker, date1, date2)
    prices.append( [q[1] for q in quotes] )

df = pd.DataFrame( prices ).transpose()
df.columns = tickers
df.head()

fig = plotly_tools.get_subplots(rows=6, columns=6, print_grid=True, horizontal_spacing= 0.05, vertical_spacing= 0.05)

    """Kernel Density Estimation with Scipy"""
Beispiel #4
0
def send():
    if request.method == 'POST':

       # just output to json file
        students = int(request.form['n-students'])
        layoutData = list(map(int, request.form['layout-data'].splitlines()))
        #layoutData = [int(i) for i in request.form['layout-data']]
        femaleRatio = float(request.form['female-ratio'])
        maleRatio = float(request.form['male-ratio'])
        otherRatio = float(request.form['other-ratio'])
        poorRatio = float(request.form['poor-ratio'])
        middleClassRatio = float(request.form['middle-class-ratio'])
        wealthyRatio = float(request.form['wealthy-ratio'])
        nativeRatio = float(request.form['native-ratio'])
        eslRatio = float(request.form['esl-ratio'])

        results = {
            "students":students,
            "layoutData":layoutData,
            "femaleRatio":femaleRatio,
            "maleRatio": maleRatio,
            "otherRatio": otherRatio,
            "poorRatio": poorRatio,
            "middleClassRatio": middleClassRatio,
            "wealthyRatio": wealthyRatio,
            "nativeRatio": nativeRatio,
            "eslRatio": eslRatio
        }

        f = open('in.json', 'w')
        f.write(json.dumps(results))
        f.close()

        #retrieve input boundaries from user
        yearF = request.form['ctl_list_YearFrom']
        yearFi = int(yearF)
        weekF = request.form['ctl_list_WeekFrom']
        weekFi = int(weekF)
        yearT = request.form['ctl_list_YearTo']
        yearTi = int(yearT)
        weekT = request.form['ctl_list_WeekTo']
        weekTi = int(weekT)
        typeSelect = request.form['selectType']

        if typeSelect == "Start End":
            df = time_filter_inclusive(yearFi, weekFi, yearTi, weekTi)
            dfWS = df

            #Week Fixer
            if yearFi != yearTi:
                i = 0
                for index, row in df.iterrows():
                    if row['Year'] != yearFi:
                        count = row['Year'] - yearFi
                        dfWS.iat[i, 1] = row['Week'] + (count * 52)
                    i += 1
            
            #create graph
            A_H1 = Scatter(x = dfWS['Week'], y = dfWS['AH1'], mode = 'markers', name = 'A (H1)')
            A_H1N1 = Scatter(x = dfWS['Week'], y = dfWS['AH1N12009'], mode = 'markers', name = 'A (H1N1)')
            A_H3 = Scatter(x = dfWS['Week'], y = dfWS['AH3'], mode = 'markers', name = 'A (H3)')
            A_H5 = Scatter(x = dfWS['Week'], y = dfWS['AH5'], mode = 'markers', name = 'A (H5)')
            A_NoSub = Scatter(x = dfWS['Week'], y = dfWS['ANOTSUBTYPED'], mode = 'markers', name = 'A (No subtype)')
            A_Total = Scatter(x = dfWS['Week'], y = dfWS['INF_A'], mode = 'markers', name = 'A Total')
            B_Yamagata = Scatter(x = dfWS['Week'], y = dfWS['BYAMAGATA'], mode = 'markers', name = 'B (Yamagata)')
            B_Victoria = Scatter(x = dfWS['Week'], y = dfWS['BVICTORIA'], mode = 'markers', name = 'B (Victoria)')
            B_NoLineage = Scatter(x = dfWS['Week'], y = dfWS['BNOTDETERMINED'], mode = 'markers', name = 'B (No lineage)')
            B_Total = Scatter(x = dfWS['Week'], y = dfWS['INF_B'], mode = 'markers', name = 'B Total')
            data = [A_H1, A_H1N1, A_H3, A_H5, A_NoSub, A_Total, B_Yamagata, B_Victoria, B_NoLineage, B_Total]
            first_plot_url = py.plot(data, filename='Inclusive Graph', auto_open=False,)
            firsttPlotHTML = plotly_tools.get_embed(first_plot_url)
        else:
            df = time_filter_weekly(yearFi, weekFi, yearTi, weekTi)
            dfWS = df

            #Week Fixer
            if yearFi != yearTi:
                i = 0
                for index, row in df.iterrows():
                    if row['Year'] != yearFi:
                        count = row['Year'] - yearFi
                        dfWS.iat[i, 1] = row['Week'] + (count * 52)
                    i += 1
            
            #create graph
            A_H1 = Scatter(x = dfWS['Week'], y = dfWS['AH1'], mode = 'markers', name = 'A (H1)')
            A_H1N1 = Scatter(x = dfWS['Week'], y = dfWS['AH1N12009'], mode = 'markers', name = 'A (H1N1)')
            A_H3 = Scatter(x = dfWS['Week'], y = dfWS['AH3'], mode = 'markers', name = 'A (H3)')
            A_H5 = Scatter(x = dfWS['Week'], y = dfWS['AH5'], mode = 'markers', name = 'A (H5)')
            A_NoSub = Scatter(x = dfWS['Week'], y = dfWS['ANOTSUBTYPED'], mode = 'markers', name = 'A (No subtype)')
            A_Total = Scatter(x = dfWS['Week'], y = dfWS['INF_A'], mode = 'markers', name = 'A Total')
            B_Yamagata = Scatter(x = dfWS['Week'], y = dfWS['BYAMAGATA'], mode = 'markers', name = 'B (Yamagata)')
            B_Victoria = Scatter(x = dfWS['Week'], y = dfWS['BVICTORIA'], mode = 'markers', name = 'B (Victoria)')
            B_NoLineage = Scatter(x = dfWS['Week'], y = dfWS['BNOTDETERMINED'], mode = 'markers', name = 'B (No lineage)')
            B_Total = Scatter(x = dfWS['Week'], y = dfWS['INF_B'], mode = 'markers', name = 'B Total')
            data = [A_H1, A_H1N1, A_H3, A_H5, A_NoSub, A_Total, B_Yamagata, B_Victoria, B_NoLineage, B_Total]
            first_plot_url = py.plot(data, filename='Inclusive Graph', auto_open=False,)
            firsttPlotHTML = plotly_tools.get_embed(first_plot_url)

        #create html raw data table
        dfRaw = df.to_html().replace('<table border="1" class="dataframe">','<table class="table table-striped">') #Table of raw data
        dfRaw = dfRaw.replace("<thead>",'<thead class="thead-dark">')

        #Run data analysis
        df.drop('Year', axis=1, inplace=True)
        df.drop('Week', axis=1, inplace=True)
        dfSum = df.describe()

        #create html summary table
        dfSum = dfSum.to_html().replace('<table border="1" class="dataframe">','<table class="table table-striped">')  #Table of analyzed data
        dfSum = dfSum.replace("<thead>",'<thead class="thead-dark">')
        os.remove("/Users/jiabeiluo/Desktop/studentrngdemo/templates/result.html")   #clear old results

        #HTML code for the results
        html_string = '''
        <html>
        <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>

        <title>Results</title>

        <style>
        body {
            position: relative;
        }
        </style>

        </head>

            <body data-spy="scroll" data-target=".navbar" data-offset="50">

    <!--NarBar-->
    <nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link" href="#section1">Data Selection Graph</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#section2">Full Data Selection Results</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#section3">Summary table</a>
        </li>
      </ul>
    </nav>

    <div id="section1" class="container-fluid" style="padding-top:70px;padding-bottom:70px">
      <div class="container">
        <div class="pb2 mt-4 mb-2 border-bottom">
          <h2>Data Selection Graph</h2>
        </div>
      </div>
      ''' + firsttPlotHTML + '''
    </div>

    <div id="section2" class="container-fluid" style="padding-top:70px;padding-bottom:70px">
      <div class="container">
        <div class="pb2 mt-4 mb-2 border-bottom">
          <h3>Full Data Selection Results</h3>
        </div>
      </div>
                ''' + dfRaw + '''
    </div>

    <div id="section3" class="container-fluid" style="padding-top:70px;padding-bottom:70px">
        <div class="container">
            <div class="pb2 mt-4 mb-2 border-bottom">
                <h3>Summary table: Data Selection Results</h3>
            </div>
        </div>
                ''' + dfSum + '''
        </div>
            </body>
        </html>'''

        #create the HTML file 
        
        f = open('/Users/jiabeiluo/Desktop/studentrngdemo/templates/result.html','w')
        f.write(html_string)
        f.close()
        
        #Return results to user
        return render_template('result.html')

    return render_template('my-form.html')
Beispiel #5
0
N = 40
x = np.linspace(0, 1, N)
y = np.random.randn(N)
df = pd.DataFrame({'x': x, 'y': y})
df.head()

data = [
    go.Bar(
        x=df['x'], # assign x as the dataframe column 'x'
        y=df['y']
    )
]

# IPython notebook
# py.iplot(data, filename='pandas-bar-chart')

url = py.plot(data, filename='pandas-bar-chart')


# In[197]:


data=db['mc_tweets_to_plot']
data_df =pd.DataFrame(list(data.find({})))

#tweets_to_plot_json = tweets_to_plot_df.to_json(orient='index')
# with open('data.txt', 'w') as outfile:  
#     json.dump(tweets_to_plot_json , outfile)
data_df.to_csv('twitterdata.csv')

Beispiel #6
0
# -*- coding: utf-8 -*-
"""
Created on Thu Aug  1 10:26:23 2019

@author: STEM
"""

import pandas as pd
import plotly
import plotly.offline as plot
import plotly.graph_objs as go

wodf = pd.read_excel("GISdata.xlsx", sheet_name="womenOccupation")
wodf

womenoccupation = go.Bar(x=wodf["occupation"],
                         y=wodf["women"],
                         marker={
                             "color": wodf["women"],
                             "colorscale": "Jet"
                         })

plot([womenoccupation])
Beispiel #7
0
    window = np.ones(int(window_size))/float(window_size)
    return np.convolve(interval, window, 'same')

date1 = dt_date( 2014, 1, 1 )
date2 = dt_date( 2014, 12, 12 )
quotes = quotes_historical_yahoo('AAPL', date1, date2)
if len(quotes) == 0:
    print "Couldn't connect to yahoo trading database"
else:
    dates = [q[0] for q in quotes]
    y = [q[1] for q in quotes]
    for date in dates:
        x.append(datetime.fromordinal(int(date))\
                .strftime('%Y-%m-%d')) # Plotly timestamp format
    ma = moving_average(y, 10)


#Now graph the data with Plotly. See here for Plotly's line plot
#syntax and here for getting started with the Plotly Python client.
xy_data = Scatter( x=x, y=y, mode='markers', marker=Marker(size=4), name='AAPL' )
# vvv clip first and last points of convolution
mov_avg = Scatter( x=x[5:-4], y=ma[5:-4], \
                  line=Line(width=2,color='red',opacity=0.5), name='Moving average' )
data = Data([xy_data, mov_avg])

py.iplot(data, filename='apple stock moving average')

#Save the plot URL - we'll use it when generating the report later.
first_plot_url = py.plot(data, filename='apple stock moving average', auto_open=False,)
print first_plot_url
Beispiel #8
0
layout = dict(title='Explained variance by different principal components',
              yaxis=dict(title='Explained variance in percent'),
              annotations=list([
                  dict(
                      x=1.16,
                      y=1.05,
                      xref='paper',
                      yref='paper',
                      text='Explained Variance',
                      showarrow=False,
                  )
              ]))

fig = dict(data=data, layout=layout)
py.plot(fig)

#得到前四个的因子的projection结果
matrix_w = np.hstack(
    (eig_pairs[0][1].reshape(13, 1), eig_pairs[1][1].reshape(13, 1),
     eig_pairs[2][1].reshape(13, 1), eig_pairs[3][1].reshape(13, 1)))
matrix_w.index = factor_list
'''
                        0         1         2         3
downside_risk_2 -0.478293 -0.137210  0.384094  0.069760
status_dsr      -0.061976 -0.062509  0.211771  0.309597
illiq_2_2        0.249994  0.119395  0.377741 -0.505791
returns_p       -0.004464 -0.017830 -0.031858  0.013654
creditRate      -0.170669  0.571809  0.004226 -0.081692
default_spread   0.000000  0.000000  0.000000  0.000000
log_trade_value  0.264545  0.140962  0.461324 -0.405704
def plotly_map_r_e_locations():
    try:
        trace1 = dict(type='scattergeo',
                      locationmode='USA-states',
                      lon=event_lon_vals,
                      lat=event_lat_vals,
                      text=event_text_vals,
                      mode='markers',
                      marker=dict(size=20, symbol='star', color='red'))
        trace2 = dict(type='scattergeo',
                      locationmode='USA-states',
                      lon=restaurant_lon_vals,
                      lat=restaurant_lat_vals,
                      text=restaurant_text_vals,
                      mode='markers',
                      marker=dict(size=8, symbol='circle', color='blue'))

        data = [trace1, trace2]

        min_lat = 10000
        max_lat = -10000
        min_lon = 10000
        max_lon = -10000

        lat_vals = event_lat_vals + restaurant_lat_vals
        lon_vals = event_lon_vals + restaurant_lon_vals
        for str_v in lat_vals:
            v = float(str_v)
            if v < min_lat:
                min_lat = v
            if v > max_lat:
                max_lat = v
        for str_v in lon_vals:
            v = float(str_v)
            if v < min_lon:
                min_lon = v
            if v > max_lon:
                max_lon = v

        center_lat = (max_lat + min_lat) / 2
        center_lon = (max_lon + min_lon) / 2

        max_range = max(abs(max_lat - min_lat), abs(max_lon - min_lon))
        padding = max_range * .10
        lat_axis = [min_lat - padding, max_lat + padding]
        lon_axis = [min_lon - padding, max_lon + padding]

        layout = dict(
            title='Local Restaurants and Events<br>(Hover for site names)',
            geo=dict(scope='usa',
                     projection=dict(type='albers usa'),
                     showland=True,
                     landcolor="rgb(250, 250, 250)",
                     subunitcolor="rgb(100, 217, 217)",
                     countrycolor="rgb(217, 100, 217)",
                     lataxis={'range': lat_axis},
                     lonaxis={'range': lon_axis},
                     center={
                         'lat': center_lat,
                         'lon': center_lon
                     },
                     countrywidth=3,
                     subunitwidth=3),
        )

        fig = dict(data=data, layout=layout)
        py.plot(fig, filename='restaurants_and_local_events')
    except ValueError:
        pass
Beispiel #10
0
 def do_display_graph(self, graph):
     plt.plot(self.graph_data)
Beispiel #11
0
else:
    dates = [q[0] for q in quotes]
    y = [q[1] for q in quotes]
    for date in dates:
        x.append(datetime.fromordinal(int(date))\
                .strftime('%Y-%m-%d')) # Plotly timestamp format
    ma = moving_average(y, 10)

# ************************* END importing AAPL INFO

# Graph Creation
xy_data = go.Scatter(x=x,
                     y=y,
                     mode='markers',
                     marker=dict(size=4),
                     name='AAPL')
# vvv clip first and last points of convolution
mov_avg = go.Scatter( x=x[5:-4], y=ma[5:-4], \
                  line=dict(width=2,color='red',opacity=0.5), name='Moving average' )
data = [xy_data, mov_avg]

py.iplot(data, filename='apple stock moving average')

# Graph URL

first_plot_url = py.plot(
    data,
    filename='apple stock moving average',
    auto_open=False,
)
print(first_plot_url)
Beispiel #12
0
    # table_ekf_output

import plotly.offline as py
from plotly.graph_objs import *

# estimations
trace1 = Scatter(x=table_ekf_output['px_est'],
                 y=table_ekf_output['py_est'],
                 xaxis='x2',
                 yaxis='y2',
                 name='KF- Estimate',
                 fillcolor='rgb(255,0,0)',
                 mode='markers')

# Measurements
trace2 = Scatter(x=table_ekf_output['px_meas'],
                 y=table_ekf_output['py_meas'],
                 xaxis='x2',
                 yaxis='y2',
                 name='Measurements',
                 fillcolor='rgb(255,255,255)',
                 mode='markers')

data = [trace1, trace2]

layout = Layout(xaxis2=dict(anchor='x2', title='px'),
                yaxis2=dict(anchor='y2', title='py'))

fig = Figure(data=data, layout=layout)
py.plot(fig, filename='EKF')
def plot_data():
    DATA_FILE_PATH = 'flightComputer.csv'

    DATA_LABELS = {
        'time': 0,
        'acceleration_x': 1,
        'acceleration_y': 2,
        'acceleration_z': 3,
        'rotation_x': 4,
        'rotation_y': 5,
        'rotation_z': 6,
        'pressure': 7,
        'temperature': 8,
        'altitude': 9,
        'events': 10
    }

    ###LIST FOR TRACES
    ##NOTE: CHANGE THE COLUMNS ACCORDING TO THE XLS DATA FROM FLIGHT COMP
    time = []  #column 1 i.e 0 WILL BE THE X FOR ALL VALUES
    acceleration = []
    acceleration_x = []  #column 6 in xls, 5 in py
    acceleration_y = []  #column 6 in xls, 5 in py
    acceleration_z = []  #column 6 in xls, 5 in py

    rotation_x = []
    rotation_y = []
    rotation_z = []

    air_pressure = []  #col 51 in xls, 50 in py
    temperature = []  #col 50 in xls, 49 in py

    velocity = []  #col 5 in xls, 4 in py
    altitude = []  #col 2 in xls, 1 in py
    inertia = []  #col 23 in xls, 22 in py
    thrust = []  #col 29 in xls, 28 in py

    data = []
    stop_time = 0
    with open(DATA_FILE_PATH, newline='') as csvfile:
        data_reader = csv.reader(csvfile, delimiter=',', quotechar='|')

        for n, row in enumerate(data_reader):

            if n == 0:
                print(len(row))
                for i in range(len(row)):
                    data.append([])

            for i in range(len(row)):

                try:
                    data[i].append(int(row[i]))

                except:
                    data[i].append(float(row[i]))
    data = np.array(data)
    data = data.astype('float64')
    print(data[DATA_LABELS['pressure']])

    endIndex = 0
    diffs = np.diff(data[DATA_LABELS['time']])
    print(diffs)
    for p, val in enumerate(diffs):
        print(val)
        if val > 50.0:
            endIndex = p - 1
            print("endIndex: {}".format(endIndex))
            break

    #Data conditioning
    for key in DATA_LABELS.keys():
        print(key)

        if 'acceleration' in key:
            print(key)
            data[DATA_LABELS[key]] = data[DATA_LABELS[key]] / (2**15) * 12
            print(data[DATA_LABELS[key]][1])

        if 'temperature' in key:
            print(key)
            data[DATA_LABELS[key]] = data[DATA_LABELS[key]] / 100
            print(data[DATA_LABELS[key]][1])

        if 'pressure' in key:
            print(key)
            data[DATA_LABELS[key]] = data[DATA_LABELS[key]] / 100000
            print(data[DATA_LABELS[key]][1])

        if 'time' in key:
            print(key)
            data[DATA_LABELS[key]] = data[DATA_LABELS[key]] / 1000
            print(data[DATA_LABELS[key]][1])

        # data[DATA_LABELS[key]] = data[DATA_LABELS[key]][:endIndex]

    ##Accleration trace
    trace1 = {
        'x': data[DATA_LABELS['time']]
        [:endIndex],  #put the x values here, they are same for all i.e time
        'y': data[DATA_LABELS['acceleration_x']]
        [:endIndex],  #put the y values i want, i.e this is acceleration column
        'mode': 'lines',  #want a line curve
        'name':
        'ACCELERATION X (m/s^2)',  #name of the trace i want i.e name of y
        'type': 'scatter',  #want to create scatter plots of these values
        'xaxis': 'x',
        'yaxis': 'y'
    }

    trace2 = {
        'x': data[DATA_LABELS['time']][:endIndex],
        'y': data[DATA_LABELS['acceleration_y']][:endIndex],
        'mode': 'lines',
        'name': 'ACCELERATION Y (m/s)',
        'type': 'scatter',
        'xaxis': 'x',
        'yaxis': 'y'
    }

    trace3 = {
        'x': data[DATA_LABELS['time']][:endIndex],
        'y': data[DATA_LABELS['acceleration_z']][:endIndex],
        'mode': 'lines',
        'name': 'ACCELERATION Z',
        'type': 'scatter',
        'xaxis': 'x',
        'yaxis': 'y'
    }

    trace4 = {
        'x': data[DATA_LABELS['time']][:endIndex],
        'y': data[DATA_LABELS['altitude']][:endIndex],
        'mode': 'lines',
        'name': 'Altitude (m)',
        'type': 'scatter',
        'xaxis': 'x',
        'yaxis': 'y'
    }

    trace5 = {
        'x': data[DATA_LABELS['time']][:endIndex],
        'y': data[DATA_LABELS['events']][:endIndex],
        'mode': 'lines',
        'name': 'Events',
        'type': 'scatter',
        'xaxis': 'x',
        'yaxis': 'y'
    }

    trace6 = {
        'x': data[DATA_LABELS['time']][:endIndex],
        'y': data[DATA_LABELS['pressure']][:endIndex],
        'mode': 'lines',
        'name': 'AIR PRESSURE (kPa)',
        'type': 'scatter',
        'xaxis': 'x',
        'yaxis': 'y'
    }

    trace7 = {
        'x': data[DATA_LABELS['time']][:endIndex],
        'y': data[DATA_LABELS['temperature']][:endIndex],
        'mode': 'lines',
        'name': 'TEMPERATURE (C)',
        'type': 'scatter',
        'xaxis': 'x',
        'yaxis': 'y'
    }

    #do same for all the components i want
    data = [trace1, trace2, trace3, trace4, trace5, trace6,
            trace7]  #put the name of all the traces
    #
    layout = {
        "autosize": True,
        "dragmode": "pan",
        "showlegend": True,
        "title": {
            #    "x": 0.48,
            "font": {
                "size": 20
            },
            "text": "FLIGHT DATA ANALYSIS (UMSATS ROCKETRY)"
        },
        "xaxis": {
            "autorange": True,
            "range": [0, 180.91],
            "rangeslider": {
                "autorange": True,
                "range": [0, 180.91],
                "visible": False
            },
            "title": {
                "text": "Time (s)"
            },
            "type": "linear"
        },
        "yaxis": {
            "autorange": True,
            "range": [-173.70122222222219, 3205.563222222222],
            "showspikes": False,
            "title": {
                "text": "Flight data"
            },
            "type": "linear"
        }
    }

    fig = dict(data=data, layout=layout)
    ply.plot(fig, filename='app/templates/Plot.html', auto_open=False)
Beispiel #14
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 11 17:34:30 2018

@author: batman
"""
print_imports()

import plotly as py
py.plotly.plotly.tools.set_credentials_file(username='******', api_key='1hy2cho61mYO4ly5R9Za')
import plotly.graph_objs as pg

trace0 = pg.Scatter(
    x=[1, 2, 3, 4],
    y=[10, 15, 13, 17]
)
trace1 = pg.Scatter(
    x=[1, 2, 3, 4],
    y=[16, 5, 11, 9]
)
data = pg.Data([trace0, trace1])

py.plot(data, filename = 'basic-line')

py.offline.plot({
    "data": [pg.Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
    "layout": pg.Layout(title="hello world")
})
Beispiel #15
0
def plotClusters(data):
    '''
    Use the plotly API to plot data from clusters.

    Gets a plot URL from plotly and then uses subprocess to 'open' that URL
    from the command line. This should open your default web browser.
    '''

    # List of symbols each cluster will be displayed using
    symbols = ['circle', 'cross', 'triangle-up', 'square']

    # Convert data into plotly format.
    traceList = []
    for i, c in enumerate(data):
        data = []
        for p in c.points:
            data.append(p.coords)
        # Data
        trace = {}
        trace['x'], trace['y'] = zip(*data)
        trace['marker'] = {}
        trace['marker']['symbol'] = symbols[i]
        trace['name'] = "Cluster " + str(i)
        traceList.append(trace)
        # Centroid (A trace of length 1)
        centroid = {}
        centroid['x'] = [c.centroid.coords[0]]
        centroid['y'] = [c.centroid.coords[1]]
        centroid['marker'] = {}
        centroid['marker']['symbol'] = symbols[i]
        centroid['marker']['color'] = 'rgb(200,10,10)'
        centroid['name'] = "Centroid " + str(i)
        traceList.append(centroid)

    # Log in to plotly
    #py = plotly(username=PLOTLY_USERNAME, key=PLOTLY_KEY)

    # Style the chart
    ''' datastyle = {'mode': 'markers',
                 'type': 'scatter',
                 'marker': {'line': {'width': 0},
                            'size': 12,
                            'opacity': 0.6,
                            'color': 'rgb(74, 134, 232)'}}

    resp = py.plot(*traceList, style=datastyle)

    # Display that plot in a browser
    cmd = "open " + resp['url']
    subprocess.call(cmd, shell=True)'''

    # Style the chart
    layout = dict(
        title='Plot',
        xaxis=dict(title='X axis'),
        yaxis=dict(title='Y axis'),
        plot_bgcolor='lightblue',
    )

    fig = dict(data=traceList, layout=layout)
    py.offline.iplot(fig)

    resp = py.plot(*traceList, style=layout)

    # Display that plot in a browser
    cmd = "open " + resp['url']
    subprocess.call(cmd, shell=True)
Beispiel #16
0
    x=table_ekf_output['px_gt'],
    y=table_ekf_output['py_gt'],
    xaxis='x2',
    yaxis='y2',
    name='Ground Truth',
    mode='markers'
)

data = [trace1, trace2, trace3]

layout = Layout(
    xaxis2=dict(

        anchor='x2',
        title='px'
    ),
    yaxis2=dict(

        anchor='y2',
        title='py'
    )
)

fig = Figure(data=data, layout=layout)
py.plot(fig, filename='EKF')

x=table_ekf_output['px_est'],
y=table_ekf_output['py_est'],
py.plot(x,y,color='blue',linestyle='solid',marker='o') 

Beispiel #17
0
plt.hist(cell['Age'], color='green', edgecolor='black')
plt.xlabel('Age')
plt.ylabel('Smoke')  #correct the label 'smoke' isnt right
plt.title('Figure 7: for Age Levels')
plt.show()

#Boxplot
plt.boxplot(cell['Calories'])
plt.xlabel('Number of Calories')
plt.title('Figure 8: Boxplot of Caloric Intake')
plt.show()

plt.boxplot(cell['Fat'])
plt.xlabel('Fat Levels')
plt.title('Figure 9: Boxplot of Fat Levels')
plt.show()

plt.plot(cell['Age'])
plt.xlabel('Age of Smokers')
plt.title('Figure 10: Boxplot of Fat Levels')
plt.show()

#Tables Rel. Freq.
print(cell['Calories'].value_counts())
a = pd.crosstable(cell.Calories, columns='Calories')
print(s)

s_rel = a / a.sum()
print(s_rel)
Beispiel #18
0
        return '重要保持客户'
    elif x == '低低高':
        return '重要挽留客户'
    elif x == '高高低':
        return '一般价值客户'
    elif x == '高低低':
        return '一般发展客户'
    elif x == '低高低':
        return '一般保持客户'
    else:
        return '一般挽留客户'


rfm['用户等级'] = rfm['value'].apply(trans_value)
rfm['用户等级'].value_counts()
trade_basic = [
    go.Bar(x=rfm['用户等级'].value_counts().index,
           y=rfm['用户等级'].value_counts().values,
           marker=dict(color='orange'),
           opacity=0.50)
]
layout = go.Layout(title='用户等级情况', xaxis=dict(title='用户重要度'))
figure_basic = go.Figure(data=trade_basic, layout=layout)
py.plot(figure_basic)
# trace = [go.Pie(labels= rfm['用户等级'].value_counts().index, values=rfm['用户等级'].value_counts().values,textfont=dict(size=12,color='white'))]
# layout2 = go.Layout(title='用户等级比例')
# figure_basic2 = go.Figure(data= trace,layout=layout2)
# py.plot(figure_basic2)

#结论和建议
             paso = paso + 1    
        else:
             paso = paso + np.random.randint(1,7)
             
        if np.random.rand() <= 0.001:
            paso = 0
        
        caminata_aleatoria.append(paso) #Agregar el numero que se creo

        Todas.append(caminata_aleatoria)

#Al terminar de correr obtenemos una caminata aleatoria el cual nombraremos Todas

#Graficaremos los resultados obtenidos.
np_Todas = np.array(Todas) #Convertimos en array el objeto Todas
plt.plot(np_Todas)
plt.show()
plt.clf()

np_Todas_transpuesta = np.transpose(np_Todas)
plt.plot(np_Todas_transpuesta)
plt.show()

Final = np_Todas[-1,:]
plt.hist(Final)
plt.show()

np.mean(Final[Final > 30]) #Calculo de la media de datos que se ecuentran en la cola de datos aleatorios con un valor mayor a 30

    ################################
    #Definicion simple de funciones#