Ejemplo n.º 1
0
		def get_traces(trace,value,type,color=None,width=.2,opacity=.3):
			if not is_list(value):
				value=[value]*len(trace['y'])
			if values_minus:
				if is_list(values_minus):
					min_value=values_minus
				else:
					min_value=[values_minus]*len(trace['y'])
			else:
				min_value=value
			if 'percent' in type:
				y_up=[trace['y'][_]*(1+value[_]/100.00) for _ in range(len(value))]
				y_down=[trace['y'][_]*(1-min_value[_]/100.00) for _ in range(len(min_value))]
			else:
				y_up=[trace['y'][_]+value[_] for _ in range(len(value))]
				y_down=[trace['y'][_]-min_value[_] for _ in range(len(min_value))]
			upper=Scatter(y=y_up,mode='lines',showlegend=False,
							 line=Line(width=width),x=trace['x'])
			if 'yaxis' in trace:
				upper['yaxis']=trace['yaxis']
			if color:
				color=normalize(color)
			else:
				if 'color' in trace['line']:
					color=trace['line']['color']
				else:
					color='charcoal'
			color=to_rgba(color,opacity) if color else None
			upper['line']['color']=color
			lower=upper.copy()
			name=trace['name']+'_' if 'name' in trace else ''
			upper.update(name=name+'upper')
			color=to_rgba(normalize(color),opacity)
			lower.update(fill='tonexty',fillcolor=color,name=name+'lower',y=y_down)
			return upper,lower
Ejemplo n.º 2
0
def dataPlotlyHandler():

    py.sign_in(username, api_key)

    trace1 = Scatter(x=[],
                     y=[],
                     stream=dict(token=stream_token, maxpoints=200))

    layout = Layout(title='Hello Internet of Things 101 Data')

    fig = Figure(data=[trace1], layout=layout)

    print py.plot(fig, filename='Hello Internet of Things 101 Plotly')

    i = 0
    stream = py.Stream(stream_token)
    stream.open()

    while True:
        stream_data = dataPlotly()
        stream.write({'x': i, 'y': stream_data})
        i += 1
        time.sleep(0.25)
Ejemplo n.º 3
0
def get_trace(sensor , start = None):    
    ts,values = sensor.get_vectors( start = start )
    if len(values) > 0:
        df = pd.DataFrame().from_dict({"ts" : ts , "values" : values})
        df.index = df['ts']
        
        # Manually shiftinig out to the "correct" timezone
        tz = pytz.timezone( settings.TIME_ZONE )
        now = datetime.datetime.now( tz = tz )
        shift = now.utcoffset()
        try:
            df.index = df.index + shift
        except TypeError:
            pass

        df = df.resample('10Min').mean( )
        
        label = "%s : %s" % (sensor.parent_device.id , sensor.sensor_type)
        return Scatter( x=df.index,
                        y=df['values'],
                        name=label)
    else:
        return None
Ejemplo n.º 4
0
def graphjeetu2(request):
    query = "SELECT * FROM datepow"
    cursor.execute(query)

    rows = cursor.fetchall()

    dates = []
    values = []
    for row in rows:
        dates.append(row[0])
        values.append(row[1])

    plot_div = plot([
        Scatter(x=dates,
                y=values,
                mode='lines',
                name='test',
                opacity=0.8,
                marker_color='green')
    ],
                    output_type='div')

    return render(request, "graph.html", context={'plot_div': plot_div})
Ejemplo n.º 5
0
def scatter_nodes(pos, labels=None, color=None, opacity=1):
    # pos is the dict of node positions
    # labels is a list  of labels of len(pos), to be displayed when hovering the mouse over the nodes
    # color is the color for nodes. When it is set as None the Plotly default color is used
    # size is the size of the dots representing the nodes
    #opacity is a value between [0,1] defining the node color opacity
    L=len(pos[0])
    trace = Scatter(x=[], y=[],  mode='markers', marker = dict(
        size = 22,
        #size = 15,
        line = dict(
            width = 0.5,
            color = 'rgb(0, 0, 0)'
        )
    ))
    for k in range(L):
        trace['x'].append(pos[0][k])
        trace['y'].append(pos[1][k])
    attrib=dict(name='', text=labels , hoverinfo='text', opacity=opacity) # a dict of Plotly node attributes
    trace=dict(trace, **attrib)# concatenate the dict trace and attrib
    if color is not None:
        trace['marker']['color']=color
    return trace  
Ejemplo n.º 6
0
    def plotCumulativeAccuracies(self, classificationAccuracies, trainSize):
        """
    Creates scatter plots that show the accuracy for each category at a
    certain training size
    
    @param classificationAccuracies (dict)    Maps a category label to a list of
        lists of accuracies. Each item in the key is a list of accuracies for
        a specific training size, ordered by increasing training size.
        
    @param trainSize                (list)    Sizes of training sets for trials.
    """
        # Convert list of list of accuracies to list of means
        classificationSummaries = [
            (label, map(numpy.mean, acc))
            for label, acc in classificationAccuracies.iteritems()
        ]

        data = []
        sizes = sorted(set(trainSize))
        for label, summary in classificationSummaries:
            data.append(Scatter(x=sizes, y=summary, name=label))
        data = Data(data)

        layout = Layout(
            title='Cumulative Accuracies for ' + self.experimentName,
            xaxis=XAxis(title='Training size',
                        titlefont=Font(family='Courier New, monospace',
                                       size=18,
                                       color='#7f7f7f')),
            yaxis=YAxis(title='Accuracy',
                        titlefont=Font(family='Courier New, monospace',
                                       size=18,
                                       color='#7f7f7f')))

        fig = Figure(data=data, layout=layout)
        plot_url = py.plot(fig)
        print "Cumulative Accuracies URL: ", plot_url
Ejemplo n.º 7
0
def airlines_stats(stat_year):
    airlineManager = AirlinesManager()
    results = airlineManager.get_airline_stats()
    x = [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
        'Nov', 'Dec'
    ]
    all_years = []
    for i in range(2018, datetime.datetime.now().year + 2):
        all_years.append(i)
    for result in results:
        data1 = []
        if result['year'] == int(stat_year):
            sums = []
            airlines = result['airlines']
            for i in range(0, len(result['counters'])):
                trace = Scatter(y=(result['counters'])[i],
                                x=x,
                                name=result['airlines'][i])
                sums.append(sum(result['counters'][i]))
                data1.append(trace)

            month_plot_div = plot(data1, output_type='div')
            print(airlines)
            print(sums)
            year_plot_div = plot([Pie(labels=airlines, values=sums)],
                                 output_type='div')

            return render_template('airlines_stats.html',
                                   stats_div=Markup(month_plot_div),
                                   whole_year_stats=Markup(year_plot_div),
                                   years=all_years,
                                   current_year=stat_year)
    return render_template('airlines_stats.html',
                           stats_div="No data available",
                           whole_year_stats="No data available",
                           years=all_years)
Ejemplo n.º 8
0
    def test_figure_json_encoding(self):
        df = pd.DataFrame(columns=["col 1"], data=[1, 2, 3])
        s1 = Scatter3d(x=numeric_list, y=np_list, z=mixed_list)
        s2 = Scatter(x=df["col 1"])
        data = Data([s1, s2])
        figure = Figure(data=data)

        js1 = _json.dumps(s1, cls=utils.PlotlyJSONEncoder, sort_keys=True)
        js2 = _json.dumps(s2, cls=utils.PlotlyJSONEncoder, sort_keys=True)

        assert (js1 == '{"type": "scatter3d", "x": [1, 2, 3], '
                '"y": [1, 2, 3, null, null, null, "2014-01-05T00:00:00"], '
                '"z": [1, "A", "2014-01-05T00:00:00", '
                '"2014-01-05T01:01:01", "2014-01-05T01:01:01.000001"]}')
        assert js2 == '{"type": "scatter", "x": [1, 2, 3]}'

        # Test JSON encoding works
        _json.dumps(data, cls=utils.PlotlyJSONEncoder, sort_keys=True)
        _json.dumps(figure, cls=utils.PlotlyJSONEncoder, sort_keys=True)

        # Test data wasn't mutated
        np_array = np.array([1, 2, 3, np.NaN, np.NAN, np.Inf, dt(2014, 1, 5)])
        for k in range(len(np_array)):
            if k in [3, 4]:
                # check NaN
                assert np.isnan(np_list[k]) and np.isnan(np_array[k])
            else:
                # non-NaN
                assert np_list[k] == np_array[k]

        assert set(data[0]["z"]) == set([
            1,
            "A",
            dt(2014, 1, 5),
            dt(2014, 1, 5, 1, 1, 1),
            dt(2014, 1, 5, 1, 1, 1, 1),
        ])
Ejemplo n.º 9
0
def redraw_graph_figure(rows, selected_row_indices):
    dff = pd.DataFrame(rows)
    fig = plotly.tools.make_subplots(rows=3,
                                     cols=1,
                                     subplot_titles=(
                                         'date',
                                         'personName',
                                         'taskName',
                                     ),
                                     shared_xaxes=False)
    marker = {'color': ['#0074D9'] * len(dff)}
    for i in (selected_row_indices or []):
        marker['color'][i] = '#FF851B'
    fig.append_trace(
        Scatter(name='date',
                x=dff['date'],
                y=dff['hourSpent'],
                mode='lines+marker',
                marker=marker), 1, 1)
    fig.append_trace(
        {
            'name': 'personName',
            'x': dff['personName'],
            'y': dff['hourSpent'],
            'type': 'bar',
            'marker': marker
        }, 2, 1)
    fig.append_trace(
        {
            'name': 'taskName',
            'x': dff['taskName'],
            'y': dff['hourSpent'],
            'type': 'bar',
            'marker': marker
        }, 3, 1)
    fig['layout']['showlegend'] = True
    return fig
Ejemplo n.º 10
0
    def create_data(self):
        bin_values, bin_edges = bin_datetimes(self.kamervraag_dates,
                                              range_years=7,
                                              bin_size_days=7)
        x, y_moving_avg = movingaverage_from_histogram(bin_values,
                                                       bin_edges,
                                                       window=8)

        moving_average_scatter = Scatter(
            x=x,
            y=y_moving_avg,
            mode='lines',
            name='lopende trend',
            line=dict(
                color=COLOR_WARNING,
                width=3,
            ),
        )

        hist_data = Histogram(
            x=self.kamervraag_dates,
            autobinx=False,
            xbins=dict(start=(timezone.now() -
                              datetime.timedelta(days=7 * 365)).timestamp() *
                       1000,
                       end=timezone.now().timestamp() * 1000,
                       size=60 * 60 * 24 * 7 * 1000),
            marker=dict(color=COLOR_INFO,
                        line=dict(
                            color=COLOR_PRIMARY,
                            width=1,
                        )),
            name='vragen per week',
        )

        return [hist_data, moving_average_scatter]
Ejemplo n.º 11
0
def scatter_edges(graph, pos, line_color='#a3a3c2', line_width=1):
    '''
    Function to create a trace to represent an edge on the plot.
    Args:
        graph (NetworkX Graph): the graph to be plotted
        pos (dict): node positions on the graph
        line_color (hex str): the color of the edge
        line_width (int): the width of the edge
    Return:
        A trace object to be used on a plotly plot
    '''
    trace = Scatter(
        x=[],
        y=[],
        mode='lines',
    )
    for edge in graph.edges():
        trace['x'] += [pos[edge[0]][0], pos[edge[1]][0], None]
        trace['y'] += [pos[edge[0]][1], pos[edge[1]][1], None]
        trace['hoverinfo'] = 'none'
        trace['line']['width'] = line_width
        if line_color is not None:
            trace['line']['color'] = line_color
    return trace
Ejemplo n.º 12
0
def steps_stat_plot_view(request):

    steps_data = StepData.objects.filter(author=request.user)
    # step_dict = {event.creation_date: event.value for event in step_data}
    step_data = plot(
        [
            Scatter(
                x=[sample.creation_date for sample in steps_data],
                y=[sample.value for sample in steps_data],
                mode="lines+markers",
                name="Steps from apple watch",
                opacity=0.8,
                marker_color="blue",
            ),
        ],
        output_type="div",
    )
    return render(
        request,
        "stat_plot_steps.html",
        context={
            "step_data": step_data,
        },
    )
Ejemplo n.º 13
0
def calc_best_k(X, y):
    print LOG_INFO_TAG + 'n_neighbors choice & cross validation'
    best_k, max_score, max_scores = None, None, None
    scs, ks = [], []
    for _k in xrange(NEIGHBORS_LOWER_BOUND, NEIGHBORS_UPPER_BOUND):
        cv = KFold(shuffle=True, n_splits=5, random_state=RANDOM_STATE)
        neigh = KNeighborsClassifier(n_neighbors=_k)
        scores = cross_val_score(neigh, X=X, y=y, cv=cv)
        score = scores.mean()
        if score > max_score:
            print score, _k
            max_score = score
            max_scores = scores
            best_k = _k
        scs.append(score), ks.append(_k)
    print LOG_INFO_TAG + 'best params:', max_score, best_k, max_scores
    trace = Scatter(
        x=ks,
        y=scs,
        mode='lines',
        name='scores(neighbors)'
    )
    plot([trace])
    return best_k
Ejemplo n.º 14
0
def graph_tots(df, column, column_name, user, pl):
    import pandas as pd
    from plotly.graph_objs import Scatter, Data, Line, Figure
    from datetime import datetime

    ts = df[column] * user.get_mult()

    #To guarentee the most recent amount matches the PL display
    if column == 'tpl':
        date = datetime.now().strftime('%Y%m%d%H%M%S%f')
        ts = ts.append(pd.Series([pl.tpl], index=[date]))

    dates = pd.to_datetime(ts.index, format='%Y%m%d%H%M%S%f')

    price = Scatter(x=dates,
                    y=ts,
                    line=Line(width=2, color='blue'),
                    name=column_name)
    layout = dict(title=column_name + ' History')

    data = Data([price])
    fig = Figure(data=data, layout=layout)

    return fig
def main():
    vars = sklearn.datasets.load_boston()['feature_names']
    boston = sklearn.datasets.load_boston()['data']
    X_idx = np.where(vars == 'DIS')[0][0]
    Y_idx = np.where(vars == 'NOX')[0][0]
    X = boston[:, X_idx]
    Y = boston[:, Y_idx]

    X_mean = np.mean(X)
    Y_mean = np.mean(Y)

    # See Introduction to Statistical Learning Ch 3.1 (Fig 3.4)
    numer = sum((x - X_mean) * (y - Y_mean) for x, y in zip(X, Y))
    denom = sum((x - X_mean)**2 for x, y in zip(X, Y))
    beta_1 = numer / denom
    beta_0 = Y_mean - beta_1 * X_mean
    eqn = 'Y(hat) = %.3f %f.3x' % (beta_0, beta_1)

    print 'Determined the below line of best fit...'
    print eqn

    trace = Scatter(x=X, y=Y, mode='markers')
    name = 'Determined this regression: %s' % eqn
    plot_url = py.plot(Data([trace]), filename=name)
Ejemplo n.º 16
0
    def scatter(self,
                dataframe,
                x=None,
                y=None,
                width=None,
                height=None,
                color=None,
                title='Scatter',
                xaxis_label=None,
                yaxis_label=None,
                label=None):

        color = self.__default_options__.get('color',
                                             None) if color is None else color
        width = self.__default_options__.get('width',
                                             None) if width is None else width

        scatter = Scatter(x=dataframe[x],
                          y=dataframe[y],
                          mode='markers',
                          marker=dict(color=color))

        if label:
            scatter['text'] = dataframe[label]

        width, height = self._width_height(width, height)

        layout = Layout(title=title, width=width, height=height)

        if xaxis_label:
            layout['xaxis'] = dict(title=xaxis_label)

        if yaxis_label:
            layout['yaxis'] = dict(title=yaxis_label)

        return Figure(data=[scatter], layout=layout)
Ejemplo n.º 17
0
def cumulative_distribution(df,
                            name='Capacity Surplus',
                            title='Sewer Capacity Surplus By Length',
                            parameter='capacity_fraction',
                            cumu_param='length'):

    #sort and accumulate length
    cap = df.sort_values(by=parameter, ascending=True)
    cap['cumulated_param'] = cap[cumu_param].cumsum()
    cap['cumulated_param_frac'] = cap.cumulated_param / cap[cumu_param].sum()
    cap['cumu_miles'] = cap.cumulated_param  #/ 5280.0

    cum_cap = Scatter(
        x=cap[parameter],
        y=cap.cumulated_param_frac,
        text=[
            '<br>'.join(x) + 'mi' for x in zip(
                cap.LABEL.astype(str).tolist(),
                cap.cumu_miles.round(1).astype(str).tolist())
        ],
        name=name,
    )
    layout = Layout(
        xaxis=dict(
            #range=[-100, 100],
            range=[0, 2.5],
            title=parameter,
        ),
        yaxis=dict(title=cumu_param + ' fraction', ),
        title=title,
        hovermode='closest')

    data = [cum_cap]
    fig = Figure(data=data, layout=layout)

    return fig, data, layout
Ejemplo n.º 18
0
def create_component_charts(component_chart_data):
    for event_type, event in component_chart_data.items():
        final_data = []
        component_averages = get_component_averages(event_type, event)
        event_filename = "charts/" + event_type.lower().replace(
            " ", "_") + "_component_chart.html"
        for event_name, averages in event.items():
            bar_x_axis, bar_y_axis = prepare_chart_data(averages)
            scatter_x_axis, scatter_y_axis = prepare_chart_data(
                component_averages)
            chart_title = event_type + " Component Scores"
            final_data.append(
                Bar(x=bar_x_axis,
                    y=bar_y_axis,
                    textposition='top left',
                    name=event_name,
                    text=event_name))
        chart_layout = Layout(margin=dict(
            r=150,
            b=200,
        ), title=chart_title)
        final_data.append(
            Scatter(x=scatter_x_axis,
                    y=scatter_y_axis,
                    mode='markers',
                    name="Average Score",
                    text="Average Score",
                    marker=dict(symbol='line-ns-open',
                                color='rgb(0, 0, 0)',
                                size=1,
                                line=dict(width=75))))
        plotly.offline.plot({
            "data": final_data,
            "layout": chart_layout
        },
                            filename=event_filename)
 def yerrorbar(self,
               ax,
               X,
               Y,
               error,
               Z=None,
               color=Tango.colorsHex['mediumBlue'],
               label=None,
               error_kwargs=None,
               **kwargs):
     error_kwargs = error_kwargs or {}
     if (error.shape[0] == 2) and (error.ndim == 2):
         error_kwargs.update(
             dict(array=error[1], arrayminus=error[0], symmetric=False))
     else:
         error_kwargs.update(dict(array=error, symmetric=True))
     X, Y = np.squeeze(X), np.squeeze(Y)
     if Z is not None:
         Z = np.squeeze(Z)
         return Scatter3d(x=X,
                          y=Y,
                          z=Z,
                          mode='markers',
                          error_y=ErrorY(color=color, **error_kwargs or {}),
                          marker=Marker(size='0'),
                          name=label,
                          showlegend=label is not None,
                          **kwargs)
     return Scatter(x=X,
                    y=Y,
                    mode='markers',
                    error_y=ErrorY(color=color, **error_kwargs or {}),
                    marker=Marker(size='0'),
                    name=label,
                    showlegend=label is not None,
                    **kwargs)
Ejemplo n.º 20
0
def benchmark_telegram_scraper(limit=None):
    luigi.build([bench_pipe.ParseTelegramJSONtoCSVTask()],
                local_scheduler=True)
    structlog.configure(logger_factory=LoggerFactory())
    logging.basicConfig(level='CRITICAL')
    center = '*' * 10

    print(center, 'Telegram Scraper Processor Benchmark', center)

    time_list = []
    min_processors = 2
    max_processors = (cpu_count() * 2) + 1

    for processor in range(min_processors, max_processors):
        print(center, f'processors: {processor}', center)
        t, r = parse_telegram_member_scraper(max_processes=processor,
                                             limit=limit)
        time_list.append({'time': t, 'processors': processor})
        sleep(2)

    data = pd.DataFrame(time_list)
    trace = Scatter(x=data.processors, y=data.time)
    plot([trace], auto_open=True)
    print(data)
Ejemplo n.º 21
0
def plot(timeseries, startdate, samplingfreq, plotname):
    """ Plot a list of dictionaries, representing sampled (top) topics """
    py.sign_in(PLOTLYID, PLOTLYPASS)

    timestamps = len(timeseries)
    times = [None] * timestamps
    scatterdata = dict()

    for i in range(timestamps):
        times[i] = startdate + dt.timedelta(seconds=samplingfreq*i)    

    for timestamp in range(timestamps):
        for k in timeseries[timestamp]:
            if not k in scatterdata:
                scatterdata[k] = [0] * timestamps 
            scatterdata[k][timestamp] = timeseries[timestamp][k]

    msg("Coversion to time series finished successfully.\n")
    msg("Number of ticks: %d\n", timestamps)
    msg("Number of unique nouns: %d\n", len(scatterdata))

    data = Data([Scatter(x=times, y=scatterdata[topic], 
        name=topic) for topic in scatterdata])
    return py.plot(data, filename=plotname)
Ejemplo n.º 22
0
def testchanges_per_commit(project, commits):
    changes = []
    text = []
    for commit in commits:
        text.append(commit.revisionHash)

        file_actions = FileAction.objects(
            id__in=commit.fileActionIds).only('fileId')
        changed_file_ids = [action.fileId for action in file_actions]

        names = []
        for file_id in changed_file_ids:
            file_name = File.objects(id=file_id).only('name').get().name
            if (file_name.startswith('test') or file_name.startswith('tests') or file_name.endswith('test.py') or \
                    file_name.endswith('tests.py')) and file_name.endswith('.py'):
                names.append(file_name)
        changes.append(len(names))

    def onpick3(event):
        ind = event.ind
        print('onpick3 scatter:', ind, np.take(text, ind),
              np.take(changes, ind))

    # matplotlib
    fig, ax = plt.subplots()
    col = ax.scatter(list(range(0, len(commits))), changes, picker=True)
    fig.canvas.mpl_connect('pick_event', onpick3)
    plt.show()

    plotly.offline.plot(
        {
            "data": [Scatter(x=list(range(0, len(commits))), y=changes)],
            "layout": Layout(title="Test changes per Commit")
        },
        filename=os.path.join(path_to_plots_dir,
                              project.name + 'test_changes.html'))
Ejemplo n.º 23
0
def lineplot(xs, ys_population, title, path='', xaxis='episode'):
  max_colour, mean_colour, std_colour, transparent = 'rgb(0, 132, 180)', 'rgb(0, 172, 237)', 'rgba(29, 202, 255, 0.2)', 'rgba(0, 0, 0, 0)'

  if isinstance(ys_population[0], list) or isinstance(ys_population[0], tuple):
    ys = np.asarray(ys_population, dtype=np.float32)
    ys_min, ys_max, ys_mean, ys_std, ys_median = ys.min(1), ys.max(1), ys.mean(1), ys.std(1), np.median(ys, 1)
    ys_upper, ys_lower = ys_mean + ys_std, ys_mean - ys_std

    trace_max = Scatter(x=xs, y=ys_max, line=Line(color=max_colour, dash='dash'), name='Max')
    trace_upper = Scatter(x=xs, y=ys_upper, line=Line(color=transparent), name='+1 Std. Dev.', showlegend=False)
    trace_mean = Scatter(x=xs, y=ys_mean, fill='tonexty', fillcolor=std_colour, line=Line(color=mean_colour), name='Mean')
    trace_lower = Scatter(x=xs, y=ys_lower, fill='tonexty', fillcolor=std_colour, line=Line(color=transparent), name='-1 Std. Dev.', showlegend=False)
    trace_min = Scatter(x=xs, y=ys_min, line=Line(color=max_colour, dash='dash'), name='Min')
    trace_median = Scatter(x=xs, y=ys_median, line=Line(color=max_colour), name='Median')
    data = [trace_upper, trace_mean, trace_lower, trace_min, trace_max, trace_median]
  else:
    data = [Scatter(x=xs, y=ys_population, line=Line(color=mean_colour))]

  #TODO : check if working
  fig = go.Figure({
    'data' : data,
    'layout': dict(title=title, xaxis={'title': xaxis}, yaxis={'title': title})
    })
  fig.write_image(os.path.join(path, title + '.png'))  
Ejemplo n.º 24
0
from __future__ import absolute_import

from plotly.graph_objs import (Data, Figure, Font, Layout, Line, Margin,
                               Marker, Scatter, XAxis, YAxis)

D = dict(x1=[0, 1, 2, 3, 4, 5],
         y1=[10, 20, 50, 80, 100, 200],
         x2=[0, 1, 2, 3, 4, 5, 6],
         y2=[1, 4, 8, 16, 32, 64, 128])

SIMPLE_LINE = Figure(data=Data([
    Scatter(x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0],
            y=[10.0, 20.0, 50.0, 80.0, 100.0, 200.0],
            name='simple',
            mode='lines',
            line=Line(dash='solid', color='rgba (0, 0, 255, 1)', width=1.0),
            xaxis='x1',
            yaxis='y1')
]),
                     layout=Layout(width=640,
                                   height=480,
                                   autosize=False,
                                   margin=Margin(l=80, r=63, b=47, t=47,
                                                 pad=0),
                                   hovermode='closest',
                                   showlegend=False,
                                   xaxis1=XAxis(domain=[0.0, 1.0],
                                                range=[0.0, 5.0],
                                                type='linear',
                                                showline=True,
                                                ticks='inside',
Ejemplo n.º 25
0
                                             Endf_MT18_number)
cross_section_uranium = data[0]

energy_carbon, data = openmc.calculate_cexs(carbon_reactor_grade, 'material',
                                            Endf_MT2_number)
cross_section_carbon = data[0]

energy_tungsten, data = openmc.calculate_cexs(tungsten, 'material',
                                              Endf_MT102_number)
cross_section_tungsten = data[0]

traces = []

traces.append(
    Scatter(x=energy_beryllium,
            y=cross_section_beryllium,
            mode='lines',
            name='Beryllium (n,2n)'))

traces.append(
    Scatter(x=energy_uranium,
            y=cross_section_uranium,
            mode='lines',
            name='Uranium-235 (n,fission)'))

traces.append(
    Scatter(x=energy_carbon,
            y=cross_section_carbon,
            mode='lines',
            name='Carbon (n,elastic)'))

traces.append(
Ejemplo n.º 26
0
    def showPlotly(self):
        """

        :return:
        """
        title = " vs ".join(self.prefixes)
        imagefile = join(self.outputdir, "_".join(self.prefixes) + '.html')
        linewidth = 1.5
        markerdiam = 4
        errbarw = 3
        colors = {
            self.prefixes[0]: 'rgb(255,140,0)',
            self.prefixes[1]: 'rgb(70,130,180)'
        }
        # HistoAvg
        trace1 = []
        df = self.histodata
        for prefix in self.prefixes:
            meancol = 'MEAN_' + prefix
            semcol = 'SEM_' + prefix
            trace1.append(
                Scatter(x=df['bins'],
                        y=df[meancol],
                        name=prefix,
                        showlegend=False,
                        line=dict(width=linewidth, color=colors[prefix]),
                        marker=dict(color=colors[prefix], size=markerdiam),
                        error_y=dict(array=df[semcol],
                                     type='data',
                                     symmetric=True,
                                     color=colors[prefix],
                                     thickness=linewidth,
                                     width=errbarw)))

        # MSDAvg
        trace2 = []
        x = [str(x) for x in range(1, self.msdpoints + 1)]
        xi = [x * self.timeint
              for x in range(1, self.msdpoints + 1)]  # convert to times

        i = 0
        for file in self.msddatafiles:
            df = pd.read_csv(file)
            all = df.groupby('Cell').get_group('ALL')
            allmeans = all.groupby('Stats').get_group('Mean')
            allsems = all.groupby('Stats').get_group('SEM')
            trace2.append(
                Scatter(y=allmeans[x].iloc[0],
                        x=xi,
                        name=self.prefixes[i],
                        mode='lines+markers',
                        showlegend=False,
                        line=dict(color=colors[self.prefixes[i]],
                                  width=linewidth),
                        marker=dict(color=colors[self.prefixes[i]],
                                    size=markerdiam),
                        error_y=dict(array=allsems[x].iloc[0],
                                     type='data',
                                     symmetric=True,
                                     color=colors[self.prefixes[i]],
                                     thickness=linewidth,
                                     width=errbarw)))
            i += 1

        # Ratios
        trace3 = []
        df = self.ratiodata
        for prefix in self.prefixes:
            cols = 'Ratio_' + prefix
            trace3.append(
                Box(y=df[cols],
                    boxpoints='all',
                    showlegend=False,
                    jitter=0.3,
                    pointpos=-1.8,
                    name=prefix,
                    marker=dict(color=colors[prefix])))

        # Areas
        trace4 = []
        df = self.areadata[self.areadata['Cell'] != 'ALL']
        for prefix in self.prefixes:
            cols = 'MSD Area_' + prefix
            trace4.append(
                Box(y=df[cols],
                    boxpoints='all',
                    jitter=0.3,
                    pointpos=-1.8,
                    name=prefix,
                    marker=dict(color=colors[prefix])))

        fig = tools.make_subplots(
            rows=2,
            cols=2,
            subplot_titles=('Mean D with SEM', 'Mean MSD with SEM',
                            'Log10(D) Ratios', 'MSD Areas'))

        fig.append_trace(trace1[0], 1, 1)
        fig.append_trace(trace1[1], 1, 1)
        fig.append_trace(trace2[0], 1, 2)
        fig.append_trace(trace2[1], 1, 2)
        fig.append_trace(trace3[0], 2, 1)
        fig.append_trace(trace3[1], 2, 1)
        fig.append_trace(trace4[0], 2, 2)
        fig.append_trace(trace4[1], 2, 2)

        fig['layout'].update(height=800, width=800, title=title)
        fig['layout']['xaxis1'].update(title='Log<sub>10</sub>(D)')
        fig['layout']['yaxis1'].update(title='Relative Frequency')
        fig['layout']['xaxis2'].update(title='Time (s)')
        fig['layout']['yaxis2'].update(title='MSD (&mu;m<sup>2</sup>)')
        # fig['layout']['xaxis3'].update(title='Group')
        fig['layout']['yaxis3'].update(title='Mobile/Immobile Ratio')
        # fig['layout']['xaxis4'].update(title='Group')
        fig['layout']['yaxis4'].update(
            title='Area under curve (&mu;m<sup>2</sup>)')
        # py.plot(fig, filename=imagefile)
        offline.plot(fig, filename=imagefile)
Ejemplo n.º 27
0
from __future__ import absolute_import

from plotly.graph_objs import (Annotation, Annotations, Data, Figure, Font,
                               Layout, Line, Margin, Scatter, XAxis, YAxis)

ANNOTATIONS = Figure(data=Data([
    Scatter(x=[0.0, 1.0, 2.0],
            y=[1.0, 2.0, 3.0],
            name='_line0',
            mode='lines',
            line=Line(dash='solid', color='rgba (0, 0, 255, 1)', width=1.0),
            xaxis='x1',
            yaxis='y1'),
    Scatter(x=[0.0, 1.0, 2.0],
            y=[3.0, 2.0, 1.0],
            name='_line1',
            mode='lines',
            line=Line(dash='solid', color='rgba (0, 0, 255, 1)', width=1.0),
            xaxis='x1',
            yaxis='y1')
]),
                     layout=Layout(width=640,
                                   height=480,
                                   autosize=False,
                                   margin=Margin(l=80, r=63, b=47, t=47,
                                                 pad=0),
                                   hovermode='closest',
                                   showlegend=False,
                                   annotations=Annotations([
                                       Annotation(x=0.000997987927565,
                                                  y=0.996414507772,
Ejemplo n.º 28
0
filepath = 'stockyear2017.csv'

if not os.path.isfile(filepath):  #如果檔案不存在就建立檔案
    for i in range(1, 13):  #取1到12數字
        url_twse = urlbase + twodigit(i) + urltail  #組合網址
        res = requests.get(url_twse)  #回傳為json資料
        jdata = json.loads(res.text)  #json解析

        outputfile = open(filepath, 'a', newline='', encoding='utf-8')  #開啟儲存檔案
        outputwriter = csv.writer(outputfile)  #以csv格式寫入檔案
        if i == 1:  #若是1月就寫入欄位名稱
            outputwriter.writerow(jdata['fields'])
        for dataline in (jdata['data']):  #逐月寫入資料
            outputwriter.writerow(dataline)
        time.sleep(0.5)  #延遲0.5秒,否則有時會有錯誤
    outputfile.close()  #關閉檔案

pdstock = pd.read_csv(filepath, encoding='utf-8')  #以pandas讀取檔案
for i in range(len(pdstock['日期'])):  #轉換日期式為西元年格式
    pdstock['日期'][i] = convertDate(pdstock['日期'][i])
pdstock['日期'] = pd.to_datetime(pdstock['日期'])  #轉換日期欄位為日期格式
data = [
    Scatter(x=pdstock['日期'], y=pdstock['收盤價'], name='收盤價'),
    Scatter(x=pdstock['日期'], y=pdstock['最低價'], name='最低價'),
    Scatter(x=pdstock['日期'], y=pdstock['最高價'], name='最高價')
]
plotly.offline.iplot({  #以plotly繪圖
    "data": data,
    "layout": Layout(title='2017年個股統計圖')
})
def plot_data(data_dict):
    '''
    Plots the data on the Plotly Framework.
    '''
    py.sign_in(plotly_username, plotly_api_key)
    tls.set_credentials_file(username=plotly_username,
                                 api_key=plotly_api_key)
    layout = Layout(
                showlegend=True,
                autosize=True,
                height=800,
                width=800,
                title="MAP",
                xaxis=XAxis(
                    zerolinewidth=4,
                    gridwidth=1,
                    showgrid=True,
                    zerolinecolor="#969696",
                    gridcolor="#bdbdbd",
                    linecolor="#636363",
                    mirror=True,
                    zeroline=False,
                    showline=True,
                    linewidth=6,
                    type="linear",
                    range=[0, data_dict["length"]],
                    autorange=False,
                    autotick=False,
                    dtick=15,
                    tickangle=-45,
                    title="X co-ordinate"
                    ),
                yaxis=YAxis(
                    zerolinewidth=4,
                    gridwidth=1,
                    showgrid=True,
                    zerolinecolor="#969696",
                    gridcolor="#bdbdbd",
                    linecolor="#636363",
                    mirror=True,
                    zeroline=False,
                    showline=True,
                    linewidth=6,
                    type="linear",
                    range=[data_dict["width"], 0],
                    autorange=False,
                    autotick=False,
                    dtick=15,
                    tickangle=-45,
                    title="Y co-ordinate"
                    )
                )
    mac_history_data = data_dict['data']
    processed_data = []
    for mac, p_data in mac_history_data.items():
        if len(p_data):
            p_data = sorted(p_data, key=lambda x:x[0])
            color = color_generator()
            plot_data = Scatter(
                x=[x[1] for x in p_data],
                y=[y[2] for y in p_data],
                mode='lines + text',
                text=list(range(1, len(p_data) + 1)),
                name=mac,
                marker=Marker(color=color),
                opacity="0.6",
                legendgroup = mac,
            )
            processed_data.append(plot_data)
            
            startData = Scatter(
            x=[p_data[0][1]],
            y=[p_data[0][2]],
            mode='markers',
            marker=Marker(color=color, size="10", symbol = "triangle-left"),
            showlegend=False,
            text=["Start point " + mac],
            legendgroup=mac,
            )
            processed_data.append(startData)
            
            endData = Scatter(
            x=[p_data[-1][1]],
            y=[p_data[-1][2]],
            mode='markers',
            marker=Marker(color=color, size="10"),
            showlegend=False,
            text=["End point " + mac],
            legendgroup=mac,
            )
            processed_data.append(endData)
    data = Data(processed_data)
    fig = Figure(data=data, layout=layout)
    py.plot(fig, filename='Sample Code For History Of Clients ')
Ejemplo n.º 30
0
def test_stream_validate_layout():
    py.sign_in(un, ak)
    my_stream = py.Stream(tk)
    my_stream.open()
    my_stream.write(Scatter(x=1, y=10), layout=Layout(legend=True))
    my_stream.close()
sess.run(tf.global_variables_initializer())
train_accuracy = []
for i in range(1000):
    batch = mnist.train.next_batch(50)
    train_accuracy.append(accuracy.eval(feed_dict={x: batch[0], y_: batch[1]}))
    print("step %d, training accuracy %g" % (i, train_accuracy[-1]))
    train_step.run(feed_dict={x: batch[0], y_: batch[1]})


def fit_f(x, a, b, c, d):
    return a * x**0.5 + b * x**0.25 + c * x**0.125 + d * x**0.0625


fit_args, _ = curve_fit(fit_f, list(range(len(train_accuracy))),
                        train_accuracy)
train_accuracy_smoothed = [
    fit_f(x, *fit_args) for x in range(len(train_accuracy))
]
plot(Data([
    Scatter(y=train_accuracy, name='Train accuracy'),
    Scatter(y=train_accuracy_smoothed,
            line=dict(shape='spline'),
            name='Train accuracy (smoothed)'),
]),
     image='svg')

print("test accuracy %g" % accuracy.eval(feed_dict={
    x: mnist.test.images,
    y_: mnist.test.labels
}))
Ejemplo n.º 32
0
def test_validate_error():
    scatter = Scatter()
    scatter['invalid'] = 'something'
    scatter.validate()