Example #1
0
class OrbitPlotter3D(_BaseOrbitPlotter):
    """OrbitPlotter3D class.
    """

    def __init__(self):
        super().__init__()
        self._layout = Layout(
            autosize=True,
            scene=dict(
                xaxis=dict(
                    title="x (km)",
                ),
                yaxis=dict(
                    title="y (km)",
                ),
                zaxis=dict(
                    title="z (km)",
                ),
                aspectmode="data",  # Important!
            ),
        )

    def _plot_sphere(self, radius, color, name, center=[0, 0, 0] * u.km):
        xx, yy, zz = _generate_sphere(radius, center)
        sphere = Surface(
            x=xx.to(u.km).value, y=yy.to(u.km).value, z=zz.to(u.km).value,
            name=name,
            colorscale=[[0, color], [1, color]],
            cauto=False, cmin=1, cmax=1, showscale=False,  # Boilerplate
        )
        return sphere

    @u.quantity_input(elev=u.rad, azim=u.rad, distance=u.km)
    def set_view(self, elev, azim, distance=5 * u.km):
        x = distance * np.cos(elev) * np.cos(azim)
        y = distance * np.cos(elev) * np.sin(azim)
        z = distance * np.sin(elev)

        self._layout.update({
            "scene": {
                "camera": {
                    "eye": {
                        "x": x.to(u.km).value, "y": y.to(u.km).value, "z": z.to(u.km).value
                    }
                }
            }
        })

    def _plot_trajectory(self, trajectory, label, color, dashed):
        trace = Scatter3d(
            x=trajectory.x.to(u.km).value, y=trajectory.y.to(u.km).value, z=trajectory.z.to(u.km).value,
            name=label,
            line=dict(
                color=color,
                width=5,
                dash='dash' if dashed else 'solid',
            ),
            mode="lines",  # Boilerplate
        )
        self._data.append(trace)
Example #2
0
class OrbitPlotter2D(_BaseOrbitPlotter):
    """OrbitPlotter2D class.

    .. versionadded:: 0.9.0
    """

    def __init__(self):
        super().__init__()
        self._layout = Layout(
            autosize=True,
            xaxis=dict(
                title="x (km)",
                constrain="domain",
            ),
            yaxis=dict(
                title="y (km)",
                scaleanchor="x",
            ),
        )
        self._layout.update({
            "shapes": []
        })

    def _plot_sphere(self, radius, color, name, center=[0, 0, 0] * u.km):
        xx, yy = _generate_circle(radius, center)
        x_center, y_center, z_center = center
        trace = Scatter(x=xx.to(u.km).value, y=yy.to(u.km).value, mode='markers', line=dict(color=color, width=5,
                                                                                            dash='dash',), name=name)
        self._layout["shapes"] += (
            {
                'type': 'circle',
                'xref': 'x',
                'yref': 'y',
                'x0': (x_center - radius).to(u.km).value,
                'y0': (y_center - radius).to(u.km).value,
                'x1': (x_center + radius).to(u.km).value,
                'y1': (y_center + radius).to(u.km).value,
                'opacity': 1,
                'fillcolor': color,
                'line': {
                    'color': color,
                },
            },

        )
        return trace

    def _plot_trajectory(self, trajectory, label, color, dashed):
        trace = Scatter(
            x=trajectory.x.to(u.km).value, y=trajectory.y.to(u.km).value,
            name=label,
            line=dict(
                color=color,
                width=2,
                dash='dash' if dashed else 'solid',
            ),
            mode="lines",  # Boilerplate
        )
        self._data.append(trace)
Example #3
0
def _merge_layout(x: go.Layout, y: go.Layout) -> go.Layout:
    """Merge attributes from two layouts."""
    xjson = x.to_plotly_json()
    yjson = y.to_plotly_json()
    if 'shapes' in yjson and 'shapes' in xjson:
        xjson['shapes'] += yjson['shapes']
    yjson.update(xjson)
    return go.Layout(yjson)
Example #4
0
 def __init__(self, figure=None, dark=False):
     super().__init__(figure)
     self._layout = Layout(
         autosize=True,
         scene=dict(
             xaxis=dict(title="x (km)"),
             yaxis=dict(title="y (km)"),
             zaxis=dict(title="z (km)"),
             aspectmode="data",  # Important!
         ),
     )
     if dark:
         self._layout.template = "plotly_dark"
Example #5
0
 def __init__(self):
     super().__init__()
     self._layout = Layout(
         autosize=True,
         xaxis=dict(
             title="x (km)",
             constrain="domain",
         ),
         yaxis=dict(
             title="y (km)",
             scaleanchor="x",
         ),
     )
     self._layout.update({
         "shapes": []
     })
Example #6
0
 def __init__(self):
     super().__init__()
     self._layout = Layout(
         autosize=True,
         scene=dict(
             xaxis=dict(
                 title="x (km)",
             ),
             yaxis=dict(
                 title="y (km)",
             ),
             zaxis=dict(
                 title="z (km)",
             ),
             aspectmode="data",  # Important!
         ),
     )
Example #7
0
    def GeneRegulationNetwork(self, netthreshold, config, netconfig):

        # Transpose the dataframe to get correct format to create the network
        dfT = self.dfz.transpose()

        # Get all the TF Gene names
        tf_names = list(dfT)

        # Create a Dask Client, just in case we want parellalize the algorithm
        client = Client(processes=False)

        # create dataframe network with columns --> TF, target Gene, Importance
        if netconfig == 1:
            network = grnboost2(expression_data=dfT,
                                tf_names=tf_names,
                                client_or_address=client)
            print("grnboost2")
        else:
            network = genie3(expression_data=dfT,
                             tf_names=tf_names,
                             client_or_address=client)

        # We put a threshold because we have a lot of conections and we want to obtain a clear graph with the most representatives conected genes
        limit = network.index.size * netthreshold

        G = nx.from_pandas_edgelist(network.head(int(limit)),
                                    'TF',
                                    'target', ['importance'],
                                    create_using=nx.Graph(directed=False))

        N = len(list(G.node()))  # number of genes nodes
        V = list(G.node())  # list of genes nodes

        Edges = list(G.edges())

        layt = {
            1: nx.fruchterman_reingold_layout(G, dim=3),
            2: nx.circular_layout(G, dim=3)
        }.get(config, nx.circular_layout(G, dim=3))

        laytN = list(layt.values())

        Xn = [laytN[k][0] for k in range(N)]  # x-coordinates of nodes
        Yn = [laytN[k][1] for k in range(N)]  # y-coordinates
        Zn = [laytN[k][2] for k in range(N)]  # z-coordinates
        Xe = []
        Ye = []
        Ze = []
        for e in Edges:
            Xe += [layt[e[0]][0], layt[e[1]][0],
                   None]  # x-coordinates of edge ends
            Ye += [layt[e[0]][1], layt[e[1]][1], None]
            Ze += [layt[e[0]][2], layt[e[1]][2], None]

        trace1 = Scatter3d(x=Xe,
                           y=Ye,
                           z=Ze,
                           mode='lines',
                           line=Line(color='rgb(125,125,125)', width=1),
                           hoverinfo='none')

        trace2 = Scatter3d(x=Xn,
                           y=Yn,
                           z=Zn,
                           mode='markers+text',
                           textposition='top center',
                           name='genes',
                           marker=Marker(symbol='circle',
                                         size=3,
                                         color='#6959CD',
                                         colorscale='Viridis',
                                         line=Line(color='rgb(50,50,50)',
                                                   width=1)),
                           text=V,
                           hoverinfo='text')

        axis = dict(showbackground=False,
                    showline=False,
                    zeroline=False,
                    showgrid=False,
                    showticklabels=False,
                    title='')

        fig = Figure(data=Data([trace1, trace2]),
                     layout=Layout(
                         title="Gene Regulatory Network",
                         width=1000,
                         height=1000,
                         showlegend=False,
                         scene=Scene(
                             xaxis=XAxis(axis),
                             yaxis=YAxis(axis),
                             zaxis=ZAxis(axis),
                         ),
                         margin=Margin(t=100),
                         hovermode='closest',
                         annotations=Annotations([
                             Annotation(showarrow=False,
                                        text="Khaos Research Group",
                                        xref='paper',
                                        yref='paper',
                                        x=0,
                                        y=0.1,
                                        xanchor='left',
                                        yanchor='bottom',
                                        font=Font(size=20))
                         ]),
                     ))

        plotly.offline.plot(fig, filename='3DNetworkx_.html', auto_open=True)
        script = plot(fig,
                      output_type='div',
                      include_plotlyjs=False,
                      show_link=True)
        #print(script)
        return script
Example #8
0
def draw_plot_graph(data, graph_title, textBaseDirName):
    plotly.offline.plot({
        "data": data,
        "layout": Layout(title=graph_title)
    },
                        filename=textBaseDirName + "_plot.html")
Example #9
0
                 name='top 10 TFs with p-value < 0.05',
                 mode='markers',
                 marker=dict(size=9, opacity=0.8),
                 textfont=dict(family='sans serif', size=11, color='black'),
                 text=list(
                     map(lambda x: "%s\n%s" % ('CistromeDB:', x),
                         final_top.loc[:, 'name_y'])),
                 hoverinfo='text',
                 textposition='top right')

layout = Layout(
    title=title,
    xaxis=dict(title='-log10(p-value) of Gene Set 1'
               if labels1.strip() == '' else '-log10(p-value) of %s' % labels1,
               showgrid=False,
               titlefont=dict(family='Arial', size=20),
               rangemode='tozero',
               range=[0, xlim]),
    yaxis=dict(title='-log10(p-value) of Gene Set 2'
               if labels2.strip() == '' else '-log10(p-value) of %s' % labels2,
               showgrid=False,
               titlefont=dict(family='Arial', size=20),
               rangemode='tozero',
               range=[0, ylim]),
    hovermode='closest',
    width=850,
    height=650)

fig = Figure(data=[top_trace0, trace1], layout=layout)
plot(fig, filename='%s.html' % prefix, show_link=False, auto_open=False)
Example #10
0
def plotClusters(data, dimensions):
    '''
	This uses the plotly offline mode to create a local HTML file.
	This should open your default web browser.
	'''
    if dimensions not in [2, 3]:
        raise Exception(
            "Plots are only available for 2 and 3 dimensional data")

    # Convert data into plotly format.
    traceList = []
    for i, c in enumerate(data):
        # Get a list of x,y coordinates for the points in this cluster.
        cluster_data = []
        for point in c.points:
            cluster_data.append(point.coords)

        trace = {}
        centroid = {}
        if dimensions == 2:
            # Convert our list of x,y's into an x list and a y list.
            trace['x'], trace['y'] = zip(*cluster_data)
            trace['mode'] = 'markers'
            trace['marker'] = {}
            trace['marker']['symbol'] = i
            trace['marker']['size'] = 12
            trace['name'] = "Cluster " + str(i)
            traceList.append(Scatter(**trace))
            # Centroid (A trace of length 1)
            centroid['x'] = [c.centroid.coords[0]]
            centroid['y'] = [c.centroid.coords[1]]
            centroid['mode'] = 'markers'
            centroid['marker'] = {}
            centroid['marker']['symbol'] = i
            centroid['marker']['color'] = 'rgb(200,10,10)'
            centroid['name'] = "Centroid " + str(i)
            traceList.append(Scatter(**centroid))
        else:
            symbols = [
                "circle", "square", "diamond", "circle-open", "square-open",
                "diamond-open", "cross", "x"
            ]
            symbol_count = len(symbols)
            if i > symbol_count:
                print("Warning: Not enough marker symbols to go around")
            # Convert our list of x,y,z's separate lists.
            trace['x'], trace['y'], trace['z'] = zip(*cluster_data)
            trace['mode'] = 'markers'
            trace['marker'] = {}
            trace['marker']['symbol'] = symbols[i]
            trace['marker']['size'] = 12
            trace['name'] = "Cluster " + str(i)
            traceList.append(Scatter3d(**trace))
            # Centroid (A trace of length 1)
            centroid['x'] = [c.centroid.coords[0]]
            centroid['y'] = [c.centroid.coords[1]]
            centroid['z'] = [c.centroid.coords[2]]
            centroid['mode'] = 'markers'
            centroid['marker'] = {}
            centroid['marker']['symbol'] = symbols[i]
            centroid['marker']['color'] = 'rgb(200,10,10)'
            centroid['name'] = "Centroid " + str(i)
            traceList.append(Scatter3d(**centroid))

    title = "K-means clustering with %s clusters" % str(len(data))
    plotly.offline.plot({"data": traceList, "layout": Layout(title=title)})
altcoin_coins = Scatter(x=blocks,
                        y=calculate_coin_count(blocks),
                        name='altcoin_coins')
block_reward = Scatter(x=calculate_years(blocks),
                       y=calculate_block_rewards(blocks),
                       name='block_reward',
                       xaxis='x2',
                       yaxis='y2')

data = [altcoin_coins, block_reward]

layout = Layout(title='Altcoin Distribution Schedule',
                xaxis=dict(title='Blocks',
                           titlefont=dict(color='rgb(148,103,189)'),
                           tickfont=dict(color='rgb(148,103,189)'),
                           domain=[0, .45]),
                xaxis2=dict(title='Year',
                            titlefont=dict(color='rgb(148,103,189)'),
                            tickfont=dict(color='rgb(148,103,189)'),
                            domain=[.55, 1]),
                yaxis2=dict(title='Block Reward',
                            titlefont=dict(color='rgb(253, 127, 40)'),
                            tickfont=dict(color='rgb(253, 127, 40)'),
                            anchor='x2',
                            overlaying='y',
                            side='right'))

fig = Figure(data=data, layout=layout)
plotly.offline.plot(fig, filename='index.html')
Example #12
0
        pair.append(curr_speed)
        pair.append(abs(delta_t.total_seconds()))
        combine.append(pair)
        Ts=curr_event
    #print combine

    total_n = 0
    for i in range(len(combine)):

        total_n+=combine[i][1]
    prod=0
    for i in range(len(combine)):
        curr_prod=(combine[i][0])*(combine[i][1])
        prod=prod+curr_prod

    final_avg=prod/total_n
    final_avg=final_avg*0.001
    print final_avg
    final_averages.append(final_avg)
print final_averages

plotly.offline.plot({
"data": [
     Scatter(x=[1,2,4,6,8,10,12,14.16,18,20,22,24], y=final_averages)

],
"layout": Layout(
    title="16-16 Server Client Architecture"
)
})
        dates.append(date)
        brightnesses.append(brightness)
        lats.append(row[0])
        lons.append(row[1])
        hover_texts.append(label)

        row_num += 1
        if row_num == num_rows:
            break

# Map the fires.
data = [{
    'type': 'scattergeo',
    'lon': lons,
    'lat': lats,
    'text': hover_texts,
    'marker': {
        'size': [brightness / 20 for brightness in brightnesses],
        'color': brightnesses,
        'colorscale': 'YlOrRd',
        'reversescale': True,
        'colorbar': {'title': 'Brightness'},
    },
}]

my_layout = Layout(title='Global Fire Activity')

fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='global_fires.html')
Example #14
0
from die import Die

# Create two D6 dice.
die_1 = Die()
die_2 = Die()

# Make some rolls, and store results in a list.
results = []
for roll_num in range(1000):
    result = die_1.roll() * die_2.roll()
    results.append(result)

# Analyze the results.
frequencies = []
max_result = die_1.num_sides * die_2.num_sides
for value in range(1, max_result + 1):
    frequency = results.count(value)
    frequencies.append(frequency)

# Visualize the results.
x_values = list(range(1, max_result + 1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': 'Result', 'dtick': 1}
y_axis_config = {'title': 'Frequency of Result'}
my_layout = Layout(title='Results of multiplying two D6 dice 1000 times',
                   xaxis=x_axis_config,
                   yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d6_d6mult.html')
Example #15
0
from plotly import offline
from die import Die

# Создание кубика D6
die = Die()

# Моделирование серии бросков с сохранением результатов в списке
results = []
for roll_num in range(1000):
    result = die.roll()
    results.append(result)

# Анализ результатов
frequencies = []
for value in range(1, die.num_sides + 1):
    frequency = results.count(value)
    frequencies.append(frequency)

# Визуализация результатов
x_values = list(range(1, die.num_sides + 1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': 'Result'}
y_axis_config = {'title': 'Frequency of Result'}
my_layout = Layout(title='Results of rolling one D6 1000 times',
                   xaxis=x_axis_config,
                   yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d6.html')

print(frequencies)
Example #16
0
    lats.append(lat)
    lons.append(lon)
    if bright > bright_min:
        brights.append(bright)

#html map plotting
from plotly.graph_objs import Scattergeo, Layout
from plotly import offline

data = [{
    "type": "scattergeo",
    "lon": lons,
    "lat": lats,
    "marker": {
        "size": [20 for bright in brights],
        "color": brights,
        "colorscale": "Viridis",
        "reversescale": True,
        "colorbar": {
            "title": "Brightness"
        },
    },
}]

my_layout = Layout(title=title)

fig = {"data": data, "layout": my_layout}

offline.plot(fig, filename="global_fires.html")
Example #17
0
        x1.append(row["date"])
        y1.append(
            ((int(row["cases"]) - previous_total1) / population[state1]) *
            100000)
        previous_total1 = int(row["cases"])
    elif row["state"] == state2:
        x2.append(row["date"])
        y2.append(
            ((int(row["cases"]) - previous_total2) / population[state2]) *
            100000)
        previous_total2 = int(row["cases"])
    elif row["state"] == state3:
        x3.append(row["date"])
        y3.append(
            ((int(row["cases"]) - previous_total3) / population[state3]) *
            100000)
        previous_total3 = int(row["cases"])

trace0 = go.Scatter(x=x1, y=y1, name=state1)
trace1 = go.Scatter(x=x2, y=y2, name=state2)
trace2 = go.Scatter(x=x3, y=y3, name=state3)

graph = {
    "data": [trace0, trace1, trace2],
    "layout":
    Layout(title=(
        f"{state1}, {state2} and {state3} comparison daily cases per 100,000"))
}

plotly.offline.plot(graph, filename="statecomparison.html")
Example #18
0
def visual():
    data = pd.read_csv('log_data/NEO_270619_01_25_04.csv')

    data['Date'] = pd.to_datetime(data['Date'])

    # startDate = data.iloc[0].Date
    # endDate = data.iloc[-1].Date
    #
    #
    # start = int(datetime.timestamp(startDate)) * 1000 + (8*60*60*1000)
    # end = int(datetime.timestamp(endDate)) * 1000 + (8*60*60*1000)
    #
    # # end = '1561702500000'
    #
    # getData('NEOUSDT',Client.KLINE_INTERVAL_15MINUTE,start=start,end=end)
    # exit()

    klines = pd.read_csv('260619_to_280619_analysis/NEOUSDT_15m.csv')

    buys = {}
    buys['date'] = []
    buys['price'] = []
    buys['target'] = []
    buys['exit'] = []
    sells = {}
    sells['date'] = []
    sells['price'] = []
    prices = {}
    prices['date'] = []
    prices['price'] = []
    for i, r in data.iterrows():

        prices['date'].append(r['Date'])
        prices['price'].append(r['Current Price'])

        if not pd.isna(r['Open Phase Exited']):
            buys['date'].append(r['Date'])
            buys['price'].append(r['Buy Price'])
            buys['target'].append(data.iloc[i + 1]['Target'])
            buys['exit'].append(data.iloc[i + 1]['Drop Threshold'])

        if not pd.isna(r['Mini Sell Price']):
            sells['date'].append(r['Date'])
            sells['price'].append(r['Mini Sell Price'])

    a = Candlestick(x=klines.DateTime,
                    open=klines.open,
                    high=klines.high,
                    low=klines.low,
                    close=klines.close)

    bolliDate = []
    bolliLow = []

    for i, r in klines.iterrows():
        if i < 8: continue

        bolliDate.append(r.DateTime)
        bolliLow.append(bollingerLow(klines.iloc[i - 5:i].close))

    bolliData = Scatter(name='Bolli',
                        x=bolliDate,
                        y=bolliLow,
                        marker=dict(color='navy', size=4))
    priceData = Scatter(name='Current Price',
                        x=prices['date'],
                        mode='lines',
                        y=prices['price'],
                        marker=dict(color='grey', size=10, symbol='star'))
    targetData = Scatter(name='target',
                         x=buys['date'],
                         y=buys['target'],
                         mode='markers',
                         marker=dict(symbol='triangle-up',
                                     color='blue',
                                     size=4))
    # miniTargetData = Scatter(name='miniTarget',x=miniTargetDate,y=miniTargetList,mode='markers',marker=dict(symbol='triangle-up',color='pink',size=3))
    #
    buyData = Scatter(name='Buy',
                      mode='markers',
                      marker=dict(symbol='circle-open-dot',
                                  color='royalblue',
                                  size=14),
                      x=buys['date'],
                      y=buys['price'])
    sellData = Scatter(name='Sell',
                       mode='markers',
                       marker=dict(symbol='star', color='black', size=14),
                       x=sells['date'],
                       y=sells['price'])
    # miniSellData = Scatter(name='miniSell',mode='markers', marker=dict(symbol='circle-open-dot',color='darkgreen', size=10), x=miniSellDate, y=miniSellPrice)
    #
    # buyStopData = Scatter(name='buyStop',mode='markers', marker=dict(symbol='diamond',color='black', size=7), x=buyOrderDate, y=buyOrderStop)
    # buyLimitData = Scatter(name='buyLimit',mode='markers', marker=dict(symbol='diamond-open',color='black', size=7), x=buyOrderDate, y=buyOrderLimit)
    #
    exitData = Scatter(name='exit',
                       mode='markers',
                       marker=dict(symbol='diamond', color='orange', size=7),
                       x=buys['date'],
                       y=buys['exit'])
    # sellLimitData = Scatter(name='sellLimit',mode='markers', marker=dict(symbol='diamond-open',color='orange', size=7), x=sellOrderDate,
    #                         y=sellOrderLimit)
    #
    # miniSellStopData = Scatter(name='miniSellStop',mode='markers', marker=dict(symbol='diamond',color='red', size=7), x=miniSellOrderDate,
    #                            y=miniSellOrderStop)
    # miniSellLimitData = Scatter(name='miniSellLimit',mode='markers', marker=dict(symbol='diamond-open',color='red', size=7), x=miniSellOrderDate,
    #                             y=miniSellOrderLimit)
    #
    # cancelData = Scatter(name='cancel',mode='markers', marker=dict(color='grey', size=7,symbol='cross'), x=cancelDate, y=cancelPrice)
    #
    majorFig = Figure(data=[
        a, priceData, bolliData, targetData, buyData, exitData, sellData
    ],
                      layout=Layout(xaxis=dict(
                          rangeslider=dict(visible=False),
                          showgrid=True,
                      )))

    print('printing graph...')
    plotly.offline.plot(
        majorFig,
        # show_link=False,
        # # output_type='div',
        # include_plotlyjs=False,
        # filename='charts//'+coin+'_'+str(seed)+'_'+ interval+ '_'+datetime.utcnow().strftime("%d%m%y_%H:%M:%S")+'.html',
        auto_open=True,
        config={
            'displaylogo':
            False,
            'modeBarButtonsToRemove': [
                'sendDataToCloud', 'select2d', 'zoomIn2d', 'zoomOut2d',
                'resetScale2d', 'hoverCompareCartesian', 'lasso2d'
            ],
            'displayModeBar':
            True
        })
    lon = eq['geometry']['coordinates'][0]
    lat = eq['geometry']['coordinates'][1]
    mags.append(mag)
    lons.append(lon)
    lats.append(lat)

print('Mags')
print(mags[:10])
print('Lons')
print(lons[:10])
print('Lats')
print(lats[:10])

from plotly.graph_objs import Scattergeo, Layout
from plotly import offline
'''
data = [Scattergeo(lon=lons, lat=lats)]
'''
data = [{
    'type': Scattergeo,
    'lon': lons,
    'lat': lats,
    'marker': {
        'size': [5 * mag for mag in mags],
    },
}]
my_layout = Layout(title='global earthquakes')

fig = {'data': data, 'layout': my_layout}

offline.plot(fig, filename='global_earthquake.html')
Example #20
0
from plotly import offline

from die import Die

# Create a D6
die_1 = Die()
die_2 = Die(10)

# make some rolls, and store the results in a list.
results = []
for roll_num in range(50_000):
    result = die_1.roll() + die_2.roll()
    results.append(result)

# Analyze the results
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2, max_result + 1):
    frequency = results.count(value)
    frequencies.append(frequency)

# Visualize the results.
x_values = list(range(2, max_result + 1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': 'Result', 'dtick': 1}
y_axis_config = {'title': 'Frequency of Result'}
my_layout = Layout(title="Results of rolling two D6 and a d10 50_000 times",
                   xaxis=x_axis_config,
                   yaxis=y_axis_config)
offline.plot({'data': data, "layout": my_layout}, filename='d6_d10.html')
    y=[],
    name='Temp',
    stream=Stream(token=stream_token_temperature  # Sets up temperature stream
                  ),
    yaxis='y')

trace_lightlevel = Scatter(
    x=[],
    y=[],
    name='Light %',
    stream=Stream(token=stream_token_lightlevel  # Sets up Lightlevel stream
                  ),
    yaxis='y2')

layout = Layout(
    title='Sun Tracker - Temperature and Lightlevel Readings',  #Labels graph
    yaxis=YAxis(title='Celcius'),
    yaxis2=YAxis(title='Light %', side='right', overlaying="y"))

#Streams the data to plotly
data = Data([trace_temperature, trace_lightlevel])
fig = Figure(data=data, layout=layout)

print py.plot(fig,
              filename='Sun Tracker - Temperature and Lightlevel Readings')

stream_temperature = py.Stream(stream_token_temperature)
stream_temperature.open()

stream_lightlevel = py.Stream(stream_token_lightlevel)
stream_lightlevel.open()
        brightnesses.append(brightness)
        date = datetime.strptime(row[5], '%Y-%m-%d')
        lat = lats.append(row[0])
        lon = lons.append(row[1])
        label = hover_texts.append(f"{date.strftime('%m-%d-%y')} - {brightness}")

        
        # Limit the data and stop the loop to prevent slow down.
        limit_data_row += 1
        if limit_data_row == limit_data_rows:
            break

# Map the fires.
data = [{
    'type': 'scattergeo',
    'lon': lons,
    'lat': lats,
    'text': hover_texts,
    'marker': {
        'size': [brightness/50 for brightness in brightnesses],
        'color': brightnesses,
        'colorscale': 'ylOrRd',
        'reversescale': True,
        'colorbar': {'title': 'Brightness'},
    }
}]

my_layout = Layout(title='Global Fire Activity - 7 Days')

fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='Projects/DataVisualization/DownloadingData/CSV_Format/global_fires.html')
        info.append(text)

# Нанесение данных на карту
data = [{
    'type':
    'scattergeo',  # Scattergeo позволяет определить данные на диаграмме карты мира
    'lon': lons,  # Долгота
    'lat': lats,  # Широта
    'text':
    info,  # Информация о месте землетрясерния при наведении мышью на маркер
    'marker': {
        'size':
        [mag * 5 for mag in mags
         ],  # Увеличение точек землетрясений для ощещния разницы в их силе
        'color':
        mags,  # Сообщает Plotly какое значение должно использоваться для определения маркера на цветовой шкале
        'colorscale':
        'Viridis',  # Какой цветовой диапозон должен использоваться
        'reversescale':
        True,  # Подобрать наиболее подходящий вариант True / False(по умолчанию)
        'colorbar': {
            'title': 'Magnitude'
        },  # Цветовой шкале рписваиватся имя для понимания значения каждого цвета
    },
}]

filename_html = f"{all_eq_data['metadata']['title']}.html"
my_layout = Layout(title='Global Earthquakes in 30 days')
fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename=filename_html)
Example #24
0
        result = sum(rolls)
    else:
        result = reduce(operator.mul, rolls, 1)
    results.append(result)

# Analyze the results.
min_result = len(dice_set) if ope == 's' else 1
max_result = sum([d.num_sides for d in dice_set]) if ope == 's' else reduce(
    operator.mul, [d.num_sides for d in dice_set], 1)
frequencies = list(
    [results.count(v) for v in range(min_result, max_result + 1)])

# Visualize the results.
x_values = list(range(min_result, max_result + 1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': "Result", 'dtick': 1}
y_axis_config = {'title': "Fequency of Result"}
dice_str = ', '.join([str(d) for d in dice_set])

my_layout = Layout(title=f"Results of rolling {dice_str} {n_rolls} times",
                   xaxis=x_axis_config,
                   yaxis=y_axis_config)
filename = dice_str = '_'.join([str(d).lower()
                                for d in dice_set]) + f'_{n_rolls}_{ope}.html'
offline.plot({
    'data': data,
    'layout': my_layout
},
             filename=f'/mnt/f/tmp/{filename}')
Example #25
0
def show_plot(data, title, filename='plot.html'):
    layout_comp = Layout(title=title)
    fig_comp = Figure(data=data, layout=layout_comp)
    plotly.offline.plot(fig_comp, filename=filename)
mags, lons, lats, hover_texts = [], [], [], []
for eq_dict in all_eq_dicts:
    mag = eq_dict["properties"]["mag"]
    lon = eq_dict["geometry"]["coordinates"][0]
    lat = eq_dict["geometry"]["coordinates"][1]
    title = eq_dict["properties"]["title"]
    mags.append(mag)
    lons.append(lon)
    lats.append(lat)
    hover_texts.append(title)

data = [{
    'type': 'scattergeo',
    'lon': lons,
    'lat': lats,
    "text": hover_texts,
    "marker": {
        "size": [3 * mag for mag in mags],
        "color": mags,
        "colorscale": "Bluered",
        "reversescale": False,
        "colorbar": {
            "title": "Magnitude"
        },
    },
}]
plot_title = all_eq_data["metadata"]["title"]
my_layout = Layout(title=plot_title)

fig = {"data": data, "layout": my_layout}
offline.plot(fig, filename="global_earthquakes.html")
Example #27
0
    longitude.append(longit)
    latitude.append(latit)

print(mags[:10])
print(longitude[:10])
print(latitude[:10])

from plotly.graph_objs import Scattergeo, Layout
from plotly import offline

data = [
    {
        "type": "scattergeo",
        "lon": longitude,
        "lat": latitude,
        "marker": {
            "size": [5 * mag for mag in mags],
            "color": mags,
            "colorscale": "Viridis",
            "reversescale": True,
            "colorbar": {"title": "Magnitude"},
        },
    }
]

my_layout = Layout(title="Global Earthquakes")

fig = {"data": data, "layout": my_layout}

offline.plot(fig, filename="global_earthquakes.html")
Example #28
0
for eq_dicts in all_eq_dicts:
    mags.append(eq_dicts['properties']['mag'])
    lons.append(eq_dicts['geometry']['coordinates'][0])
    lats.append(eq_dicts['geometry']['coordinates'][1])
    hover_text.append(eq_dicts['properties']['title'])

print(mags[:10])
print(lons[:5])
print(lats[:5])

# data = [Scattergeo(lon=lons, lat=lats)]
data = [{
    'type': 'scattergeo',
    'lon': lons,
    'lat': lats,
    'text': hover_text,
    'marker': {
        'size': [5 * mag for mag in mags],
        'color': mags,
        'colorscale': 'Viridis',
        'reversescale': True,
        'colorbar': {
            'title': 'Magnitude'
        }
    }
}]
my_layout = Layout(title={'text': title, 'x': 0.5})

fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='global_earthquakes.html')
Example #29
0
print(lats[:10])

#############################################################
from plotly.graph_objs import Scattergeo, Layout  #uses world maps
from plotly import offline

#data = [Scattergeo(lon=lons, lat=lats)] #Scattergeo needs these as arguments, basic data layouts

data = [{
    'type': 'scattergeo',
    'lon': lons,
    'lat': lats,
    'marker': {
        'size': [
            5 * mag for mag in mags
        ],  #for each magnitude in the list of magnitudes, take that magnitude and multiply by 5
        'color': mags,
        'colorscale': 'Viridis',
        'reversescale': True,
        'colorbar': {
            'title': 'Magnitude'
        }
    },
}]

my_layout = Layout(title='Global Earthquakes')

fig = {'data': data, 'layout': my_layout}

offline.plot(fig, filename='global_earthquakes.html')
Example #30
0
def graph_military_spending_over_time():
    #Generate scatter plots for each country
    data = []
    with open('data/SIPRI-Milex-data-1988-2015-cleaned-current-usd.csv'
              ) as current_usd:
        reader = csv.reader(current_usd)
        headers = next(reader, None)
        for row in reader:
            #Data unavailable, or country didn't exist at the time
            if ('. .' in row[13:] or 'xxx' in row[13:]):
                continue
            trace = Scatter(x=headers[13:],
                            y=row[13:],
                            name=row[0],
                            fill='tonexty',
                            line=dict(width=.5),
                            mode='lines',
                            textfont=dict(family='sans serif',
                                          size=30,
                                          color='#ff7f0e'))
            data.append(trace)

    #Sort scatter plots by countries with highest expenditures in 2015
    data = sorted(data, key=lambda trace: float(trace.y[-1]))

    #Layout taken from https://plot.ly/python/figure-labels/
    layout = Layout(
        title='Discretionary Military Spending 2000-2015',
        xaxis=dict(title='Year',
                   titlefont=dict(family='Courier New, monospace',
                                  size=26,
                                  color='#7f7f7f')),
        yaxis=dict(title='Millions of 2015 US dollars',
                   titlefont=dict(family='Courier New, monospace',
                                  size=26,
                                  color='#7f7f7f')),
        annotations=[
            dict(x=2009,
                 y=668567,
                 xref='x',
                 yref='y',
                 text='Obama Takes Office; deployments in Iraq winding down',
                 showarrow=True,
                 arrowhead=7,
                 ax=-120,
                 ay=-40),
            dict(x=2003,
                 y=415223,
                 xref='x',
                 yref='y',
                 text='Beginning of Iraq War',
                 showarrow=True,
                 arrowhead=7,
                 ax=-20,
                 ay=-40),
            dict(x=2011,
                 y=711338,
                 xref='x',
                 yref='y',
                 text='Official end of Iraq War',
                 showarrow=True,
                 arrowhead=7,
                 ax=0,
                 ay=-25),
            dict(x=2001,
                 y=312743,
                 xref='x',
                 yref='y',
                 text='9/11; Beginning of War in Afghanistan',
                 showarrow=True,
                 arrowhead=7,
                 ax=-20,
                 ay=-40),
            dict(x=2014,
                 y=609914,
                 xref='x',
                 yref='y',
                 text='Official End of War in Afghanistan',
                 showarrow=True,
                 arrowhead=7,
                 ax=20,
                 ay=-40)
        ])
    fig = Figure(data=data[len(data) - 15:], layout=layout)
    plot(fig, filename="images/military-spending-over-time")
import plotly as py
from plotly.graph_objs import Scatter, Layout, Figure
import numpy as np
import pandas as pd

read = pd.read_csv('DriveLog.csv')
df = read[read.driveMode == 'PATH_FOLLOWING']
startPoint = read.shape[0] - df.shape[0]
startTime = df.ix[startPoint, 'sysTime']
xaxis = (df['sysTime'] - startTime
         ) * 10E-10  #should be 10E-9 but that makes our time 10x too long?????
layout = Layout(title='DriveLog.csv graph',
                plot_bgcolor='rgb(230, 230,230)')  #,height=1500,width=1500)


def data(arg):
    return Scatter(x=xaxis, y=df[arg], mode='lines', name=arg)


#position data
leftPathPos = data('leftPathPos')
leftEncoder = data('leftEncoder')
rightPathPos = data('rightPathPos')
rightEncoder = data('rightEncoder')

#velocity data
leftPathVel = data('leftPathVel')
leftEncoderVel = data('leftEncoderVel')
rightPathVel = data('rightPathVel')
rightEncoderVel = data('rightEncoderVel')
Example #32
0
class OrbitPlotter3D(BaseOrbitPlotter):
    """OrbitPlotter3D class.

    """

    def __init__(self, figure=None, dark=False):
        super().__init__(figure)
        self._layout = Layout(
            autosize=True,
            scene=dict(
                xaxis=dict(title="x (km)"),
                yaxis=dict(title="y (km)"),
                zaxis=dict(title="z (km)"),
                aspectmode="data",  # Important!
            ),
        )
        if dark:
            self._layout.template = "plotly_dark"

    def _plot_point(self, radius, color, name, center=[0, 0, 0] * u.km):
        # We use _plot_sphere here because it's not easy to specify the size of a marker
        # in data units instead of pixels, see
        # https://stackoverflow.com/q/47086547
        return self._plot_sphere(radius, color, name, center)

    def _plot_sphere(self, radius, color, name, center=[0, 0, 0] * u.km):
        xx, yy, zz = generate_sphere(radius, center)
        sphere = Surface(
            x=xx.to(u.km).value,
            y=yy.to(u.km).value,
            z=zz.to(u.km).value,
            name=name,
            colorscale=[[0, color], [1, color]],
            cauto=False,
            cmin=1,
            cmax=1,
            showscale=False,
        )
        self._figure.add_trace(sphere)

        return sphere

    def _plot_trajectory(self, trajectory, label, color, dashed):
        trace = Scatter3d(
            x=trajectory.x.to(u.km).value,
            y=trajectory.y.to(u.km).value,
            z=trajectory.z.to(u.km).value,
            name=label,
            line=dict(color=color, width=5, dash="dash" if dashed else "solid"),
            mode="lines",  # Boilerplate
        )
        self._figure.add_trace(trace)

        return trace

    @u.quantity_input(elev=u.rad, azim=u.rad, distance=u.km)
    def set_view(self, elev, azim, distance=5 * u.km):
        x = distance * np.cos(elev) * np.cos(azim)
        y = distance * np.cos(elev) * np.sin(azim)
        z = distance * np.sin(elev)

        self._layout.update(
            {
                "scene": {
                    "camera": {
                        "eye": {
                            "x": x.to(u.km).value,
                            "y": y.to(u.km).value,
                            "z": z.to(u.km).value,
                        }
                    }
                }
            }
        )

        if not self._figure._in_batch_mode:
            return self.show()
Example #33
0
from plotly.graph_objs import Bar, Layout
from plotly import offline
from die import Die

die_1 = Die()
die_2 = Die()
die_3 = Die()

results = []
for roll_num in range(5_000_000):
    result = die_1.roll() + die_2.roll() + die_3.roll()
    results.append(result)

frequencies = []
max_result = die_1.num_sides + die_2.num_sides + die_3.num_sides
for value in range(3, max_result+1):
    frequency = results.count(value)
    frequencies.append(frequency)

x_values = list(range(3, max_result+1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': 'Result', 'dtick': 1}
y_axis_config = {'title': 'Frequency of Result'}
my_layout = Layout(title='Results of rolling THREE D8s Several Times', xaxis=x_axis_config, yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d8_d8_d8.html')

print(frequencies)
Example #34
0
    def st_map(self,
               zoom=11,
               style='mapbox://styles/rmetfc/ck1manozn0edb1dpmvtzle2cp',
               build_order=None):
        if self.dataset.node_station_info is None or len(
                self.dataset.node_station_info) == 0:
            raise ValueError('No station information found in dataset')

        import numpy as np
        import plotly
        from plotly.graph_objs import Scattermapbox, Layout

        mapboxAccessToken = "pk.eyJ1Ijoicm1ldGZjIiwiYSI6ImNrMW02YmwxbjAxN24zam9kNGVtMm5raWIifQ.FXKqZCxsFK-dGLLNdeRJHw"

        # os.environ['MAPBOX_API_KEY'] = mapboxAccessToken

        lat_lng_name_list = [e[2:] for e in self.dataset.node_station_info]
        build_order = build_order or list(
            range(len(self.dataset.node_station_info)))

        color = ['rgb(255, 0, 0)' for _ in build_order]

        lat = np.array([float(e[2]) for e in self.dataset.node_station_info
                        ])[self.traffic_data_index]
        lng = np.array([float(e[3]) for e in self.dataset.node_station_info
                        ])[self.traffic_data_index]
        text = [str(e) for e in range(len(build_order))]

        file_name = self.dataset.dataset + '-' + self.dataset.city + '.html'

        bikeStations = [
            Scattermapbox(
                lon=lng,
                lat=lat,
                text=text,
                mode='markers',
                marker=dict(
                    size=6,
                    # color=['rgb(%s, %s, %s)' % (255,
                    #                 #                             195 - e * 195 / max(build_order),
                    #                 #                             195 - e * 195 / max(build_order)) for e in build_order],
                    color=color,
                    opacity=1,
                ))
        ]

        layout = Layout(
            title=
            'Bike Station Location & The latest built stations with deeper color',
            autosize=True,
            hovermode='closest',
            showlegend=False,
            mapbox=dict(accesstoken=mapboxAccessToken,
                        bearing=0,
                        center=dict(lat=np.median(lat), lon=np.median(lng)),
                        pitch=0,
                        zoom=zoom,
                        style=style),
        )

        fig = dict(data=bikeStations, layout=layout)
        plotly.offline.plot(fig, filename=file_name)
Example #35
0
from die import Die

# Create a D6 and a D10.
die_1 = Die(8)
die_2 = Die(8)

# Numver of dice
die_count = 2

# Make some rolls, and store results in a list.
results = []
results = [(die_1.roll() + die_2.roll()) for roll_num in range(500_000)]
print(results)

# Aanlyze the results.
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
frequencies = [results.count(value) for value in range(2, max_result+1)]
print(frequencies)

# Visualize the results.
x_values = list(range(die_count, max_result+1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': 'Result', 'dtick': 1}
y_axis_config = {'title': 'Frequency of Result'}
my_layout = Layout(title='Results of rolling a D6 and a D10 dice 50000 times' , xaxis=x_axis_config, yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d8_d8.html')

print(frequencies)
    name='',
    opacity = 0.75,
    xaxis="x")

trace1 = Histogram(
    x=x2,
    name='',
    histnorm='probability',
    opacity=0.75,
    xaxis="x1")

data = [trace0, trace1]
layout = Layout(barmode='overlay', 
                title='出度和入度分布',
                xaxis1={"domain": [0, 0.5], 
                        "title": "入度"}, 
                xaxis2={"domain": [0.5, 1], 
                        "title": "出度"}
               )

fig = Figure(data=data, layout=layout)
py.offline.iplot(fig, filename='degree_chart.html')


#%%
u = list(b.values())
u.count(0)


#%%
nx.degree_assortativity_coefficient(epinions_graph)
Example #37
0
class OrbitPlotter3D(BaseOrbitPlotter):
    """OrbitPlotter3D class.

    """
    def __init__(self, figure=None, dark=False):
        super().__init__(figure)
        self._layout = Layout(
            autosize=True,
            scene=dict(
                xaxis=dict(title="x (km)"),
                yaxis=dict(title="y (km)"),
                zaxis=dict(title="z (km)"),
                aspectmode="data",  # Important!
            ),
        )
        if dark:
            self._layout.template = "plotly_dark"

    def _plot_point(self, radius, color, name, center=[0, 0, 0] * u.km):
        # We use _plot_sphere here because it's not easy to specify the size of a marker
        # in data units instead of pixels, see
        # https://stackoverflow.com/q/47086547
        return self._plot_sphere(radius, color, name, center)

    def _plot_sphere(self, radius, color, name, center=[0, 0, 0] * u.km):
        xx, yy, zz = generate_sphere(radius, center)
        sphere = Surface(
            x=xx.to(u.km).value,
            y=yy.to(u.km).value,
            z=zz.to(u.km).value,
            name=name,
            colorscale=[[0, color], [1, color]],
            cauto=False,
            cmin=1,
            cmax=1,
            showscale=False,
        )
        self._figure.add_trace(sphere)

        return sphere

    def _plot_trajectory(self, trajectory, label, color, dashed):
        trace = Scatter3d(
            x=trajectory.x.to(u.km).value,
            y=trajectory.y.to(u.km).value,
            z=trajectory.z.to(u.km).value,
            name=label,
            line=dict(color=color, width=5,
                      dash="dash" if dashed else "solid"),
            mode="lines",  # Boilerplate
        )
        self._figure.add_trace(trace)

        return trace

    @u.quantity_input(elev=u.rad, azim=u.rad, distance=u.km)
    def set_view(self, elev, azim, distance=5 * u.km):
        x = distance * np.cos(elev) * np.cos(azim)
        y = distance * np.cos(elev) * np.sin(azim)
        z = distance * np.sin(elev)

        self._layout.update({
            "scene": {
                "camera": {
                    "eye": {
                        "x": x.to(u.km).value,
                        "y": y.to(u.km).value,
                        "z": z.to(u.km).value,
                    }
                }
            }
        })

        if not self._figure._in_batch_mode:
            return self.show()
start, stop = raw.time_as_index([0, 10])

n_channels = 20
data, times = raw[picks[:n_channels], start:stop]
ch_names = [raw.info['ch_names'][p] for p in picks[:n_channels]]


# Finally, we create the plotly graph by creating a separate subplot for each channel

# In[15]:

step = 1. / n_channels
kwargs = dict(domain=[1 - step, 1], showticklabels=False, zeroline=False, showgrid=False)

# create objects for layout and traces
layout = Layout(yaxis=YAxis(kwargs), showlegend=False)
traces = [Scatter(x=times, y=data.T[:, 0])]

# loop over the channels
for ii in range(1, n_channels):
        kwargs.update(domain=[1 - (ii + 1) * step, 1 - ii * step])
        layout.update({'yaxis%d' % (ii + 1): YAxis(kwargs), 'showlegend': False})
        traces.append(Scatter(x=times, y=data.T[:, ii], yaxis='y%d' % (ii + 1)))

# add channel names using Annotations
annotations = Annotations([Annotation(x=-0.06, y=0, xref='paper', yref='y%d' % (ii + 1),
                                      text=ch_name, font=Font(size=9), showarrow=False)
                          for ii, ch_name in enumerate(ch_names)])
layout.update(annotations=annotations)

# set the size of the figure and plot it