Example #1
0
def density2d(x, y, z=None, **kwargs):
    """
    Create a histogram. Parameter `z` is for a unified API.

    Args:
        x (iterable): Values for the density x-axis.
        y (iterable): Values for the density y-axis.
        z: Not applicable.
        **kwargs: Any other keyword argument passed to `go.Histogram2dContour`.

    Returns:
        list[`go.Scatter`, `go.Histogram2dContour`]
    """

    marker = {
        "color": 'rgb(102,0,0)',
        "size": 2,
        "opacity": 0.2,
    }
    histogram_params = {
        "name": "density",
        "ncontours": 20,
        "colorscale": "Hot",
        "reversescale": True,
        "showscale": False
    }

    histogram_params.update(kwargs)

    return [
        _simple_scatter(x, y, mode='markers', marker=marker),
        go.Histogram2dContour(x=x, y=y, **histogram_params),
    ]
def make2dHist(poslist, sizelist, boundD):

    if args.g:
        geneModel = buildGeneModel()
        chartTitle = str("Gene:" + args.g + "  |||| Inputs:" + args.i),
    else:
        geneModel = []
        geneModel.insert(
            0, {
                'type': 'rect',
                'x0': min(poslist),
                'y0': 52.5,
                'x1': max(poslist),
                'y1': 55,
                'fillcolor': 'rgb(100,100,100)'
            })
        chartTitle = str("Inputs:" + args.i),

    trace1 = go.Histogram2dContour(
        x=poslist,
        y=sizelist,
        zmin=0,
        zmax=10000,
        contours=dict(showlines=False),
        colorscale=[[0, 'rgb(255,255,255)'], [0.25, 'rgb(31,120,180)'],
                    [0.45, 'rgb(178,223,138)'], [0.65, 'rgb(51,159,44)'],
                    [0.85, 'rgb(251,154,153)'], [1, 'rgb(227,26,28)']],
    )

    data = go.Data([trace1])

    layout = go.Layout(
        title=chartTitle,
        autosize=True,
        width=1800,
        height=800,
        yaxis=dict(
            title='Particle Size',
            titlefont=dict(
                family='Arial, sans-serif',
                size=18,
                #color='lightgrey'
            ),
            showgrid=True,
            type='log',
            #autorange=True
            # log 50 and log 500. Christ knows why it wont let me log it in place...
            range=[1.698970004, 2.698970004]),
        xaxis=dict(
            title="Genomic Co-ordinates",
            titlefont=dict(
                family='Arial, sans-serif',
                size=18,
                #color='lightgrey'
            )),
        shapes=geneModel)

    fig = go.Figure(data=data, layout=layout)
    outname = str(args.o) + "-2Dcontour.html"
    plotly.offline.plot(fig, filename=outname)
Example #3
0
def update_graph_graph6(xaxis_column_name, yaxis_column_name):
    return {
        'data': [
            go.Histogram2dContour(x=table[xaxis_column_name],
                                  y=table[yaxis_column_name],
                                  colorscale='Blues',
                                  reversescale=True,
                                  xaxis='x',
                                  yaxis='y'),
        ],
        'layout':
        go.Layout(autosize=False,
                  xaxis=dict(zeroline=False, showgrid=False),
                  yaxis=dict(zeroline=False, showgrid=False),
                  xaxis2=dict(zeroline=False, showgrid=False),
                  yaxis2=dict(zeroline=False, showgrid=False),
                  hovermode='closest',
                  showlegend=True,
                  plot_bgcolor=colors['background'],
                  paper_bgcolor=colors['background'],
                  margin={
                      'l': 70,
                      'b': 70,
                      't': 40,
                      'r': 0
                  },
                  font={'color': colors['text']})
    }
    def test_add_traces(self):

        # Add two traces
        self.figure.add_traces([
            go.Sankey(arrangement="snap"),
            go.Histogram2dContour(line={"color": "cyan"}),
        ])

        # Check access properties
        self.assertEqual(self.figure.data[-2].type, "sankey")
        self.assertEqual(self.figure.data[-2].arrangement, "snap")

        self.assertEqual(self.figure.data[-1].type, "histogram2dcontour")
        self.assertEqual(self.figure.data[-1].line.color, "cyan")

        # Check message
        new_uid1 = self.figure.data[-2].uid
        new_uid2 = self.figure.data[-1].uid
        self.figure._send_addTraces_msg.assert_called_once_with([
            {
                "type": "sankey",
                "arrangement": "snap"
            },
            {
                "type": "histogram2dcontour",
                "line": {
                    "color": "cyan"
                }
            },
        ])
Example #5
0
def update_heatmap(x_axis_name, y_axis_name, year_value):
    dff = df[df['year'] == year_value]

    return {
        'data': [
            go.Histogram2dContour(x=dff[x_axis_name.lower()],
                                  y=dff[y_axis_name.lower()],
                                  colorscale='Blues',
                                  reversescale=True,
                                  xaxis='x',
                                  yaxis='y'),
            go.Scatter(
                x=dff[x_axis_name.lower()],
                y=dff[y_axis_name.lower()],
                mode='markers',
                marker={
                    'color': 'rgba(0,0,0,0.3)',
                    'size': 3
                    # 'size': 15,
                    # 'opacity': 0.5,
                    # 'line': {'width': 0.5, 'color': 'white'}
                }),
            go.Histogram(y=dff[y_axis_name.lower()],
                         xaxis='x2',
                         marker=dict(color='rgba(190,186,218,0.8)')),
            go.Histogram(x=dff[x_axis_name.lower()],
                         yaxis='y2',
                         marker=dict(color='rgba(190,186,218,0.8)'))
        ],
        'layout':
        go.Layout(autosize=False,
                  xaxis={
                      'title': x_axis_name,
                      'zeroline': False,
                      'domain': [0, 0.85],
                      'showgrid': False
                  },
                  yaxis={
                      'title': y_axis_name,
                      'zeroline': False,
                      'domain': [0, 0.85],
                      'showgrid': False
                  },
                  xaxis2=dict(zeroline=False, domain=[0.85, 1],
                              showgrid=False),
                  yaxis2=dict(zeroline=False, domain=[0.85, 1],
                              showgrid=False),
                  height=300,
                  width=600,
                  bargap=0,
                  margin={
                      'l': 40,
                      'b': 40,
                      't': 10,
                      'r': 0
                  },
                  hovermode='closest',
                  showlegend=False)
    }
Example #6
0
def make2dHist(poslist, sizelist, bCount):

    if args.g:
        geneModel = buildGeneModel()
        chartTitle = str("Gene:" + args.g + "  |||| Inputs:" + args.i)
        outname = str(args.g) + "-2Dcontour.html"
    elif args.B:
        geneModel = []
        chartTitle = str("Region: " + chrom + ":" + str(min(poslist)) + "-" +
                         str(max(poslist)) + "|||| Inputs: " + args.i)
        outname = str(chrom + ":" + min(poslist) + "-" +
                      max(poslist)) + "-2Dcontour.html"
    else:
        geneModel = []
        chartTitle = str("Inputs: " + args.i + " |||| No. Regions: " +
                         str(bCount))
        outname = str(args.b) + "-2Dcontour.html"

    trace1 = go.Histogram2dContour(
        x=poslist,
        y=sizelist,
        zmin=0,
        zmax=args.z,
        contours=dict(showlines=False),
        colorscale=[[0, 'rgb(255,255,255)'], [0.25, 'rgb(31,120,180)'],
                    [0.45, 'rgb(178,223,138)'], [0.65, 'rgb(51,159,44)'],
                    [0.85, 'rgb(251,154,153)'], [1, 'rgb(227,26,28)']],
    )

    data = go.Data([trace1])

    layout = go.Layout(
        title=chartTitle,
        autosize=True,
        width=1800,
        height=800,
        yaxis=dict(
            title='Particle Size',
            titlefont=dict(
                family='Arial, sans-serif',
                size=18,
                #color='lightgrey'
            ),
            showgrid=True,
            type='log',
            #autorange=True
            # log 50 and log 500. Christ knows why it wont let me log it in place...
            range=[1, 2.698970004]),
        xaxis=dict(
            title="Genomic Co-ordinates",
            titlefont=dict(
                family='Arial, sans-serif',
                size=18,
                #color='lightgrey'
            )),
        shapes=geneModel)

    fig = go.Figure(data=data, layout=layout)
    plotly.offline.plot(fig, filename=outname)
Example #7
0
def return_densities(label, Distances={}, data={}, Centre_distances={}, Dr=''):
    select_l1 = [label]
    selected1 = [
        x for x in range(Distances.shape[0])
        if data[Dr]['labels_l1'][x] + 1 in select_l1
    ]

    x = np.mean(Distances[selected1, :], axis=0)
    y = np.mean(Centre_distances[selected1, :], axis=0)

    fig = [go.Scatter(x=x, y=y, mode='markers')]

    colorscale = [
        '#7A4579', '#D56073', 'rgb(236,158,105)', (1, 1, 0.2),
        (0.98, 0.98, 0.98)
    ]

    trace1 = go.Scatter(x=x,
                        y=y,
                        mode='markers',
                        name='points',
                        marker=dict(color='rgb(102,0,0)', size=5, opacity=0.4))
    trace2 = go.Histogram2dContour(x=x,
                                   y=y,
                                   name='density',
                                   ncontours=20,
                                   colorscale='Hot',
                                   reversescale=True,
                                   showscale=False)
    trace3 = go.Histogram(x=x,
                          name='x density',
                          marker=dict(color='rgb(102,0,0)'),
                          yaxis='y2')
    trace4 = go.Histogram(y=y,
                          name='y density',
                          marker=dict(color='rgb(102,0,0)'),
                          xaxis='x2')
    fig = {'data': [trace1, trace2, trace3, trace4]}

    fig['layout'] = go.Layout(
        showlegend=False,
        autosize=True,
        #width=1200,
        #height=550,
        xaxis=dict(domain=[0, 0.85], showgrid=False, zeroline=False),
        yaxis=dict(domain=[0, 0.85], showgrid=False, zeroline=False),
        margin=dict(t=50),
        hovermode='closest',
        bargap=0,
        xaxis2=dict(domain=[0.85, 1], showgrid=False, zeroline=False),
        yaxis2=dict(domain=[0.85, 1], showgrid=False, zeroline=False))

    iplot(fig)
Example #8
0
def Histogram2dContour():

    x = np.random.randn(2000)
    y = np.random.randn(2000)
    plot([
        go.Histogram2dContour(x=x, y=y, contours=dict(coloring='heatmap')),
        go.Scatter(x=x,
                   y=y,
                   mode='markers',
                   marker=dict(color='white', size=3, opacity=0.3))
    ],
         show_link=False,
         auto_open=False,
         filename='test_plot.html')
Example #9
0
def cont_hist(yh,
              y,
              title='2D Contour Histogram',
              xlab='Model Output',
              ylab='Y',
              subtitle=None,
              plot_dir=None,
              in_browser=False):
    """
    Make a 2D contour histogram plot of y vs yh.
    The plot is produced in the browser and optionally written to a file.
    
    :param yh: Model outputs -- nd.array or pd.Series
    :param y: Target value, same type as yh
    :param title: Title for plot
    :param xlab: x-axis label
    :param ylab: y-axis label
    :param subtitle: optional subtitle
    :param plot_dir: optional file to write graph to
    :param in_browser: if True plot to browser
    :return:
    """

    fig = [go.Histogram2dContour(x=yh, y=y)]
    min_value = min([yh.min(), y.quantile(.01)])
    max_value = max([yh.max(), y.quantile(.99)])
    fig += [
        go.Scatter(x=[min_value, max_value],
                   y=[min_value, max_value],
                   mode='lines',
                   line=dict(color='red'))
    ]

    if subtitle is not None:
        title += title + '<br>' + subtitle
    layout = go.Layout(title=dict(text=title, x=0.5),
                       height=800,
                       width=800,
                       xaxis=dict(title=xlab),
                       yaxis=dict(title=ylab))
    figx = go.Figure(fig, layout=layout)
    if in_browser:
        figx.show()
    if plot_dir is not None:
        figx.write_image(plot_dir + 'png/model_fit.png')
        figx.write_html(plot_dir + 'html/model_fit.html',
                        include_plotlyjs='cdn')
Example #10
0
def update_figure(input1):
    df1 = df[df.pitcher_id == input1]
    trace_2 = go.Histogram2dContour(x=df1.px,
                                    y=df1.pz,
                                    colorscale='Jet',
                                    zmin=1,
                                    zauto=False)
    fig = go.Figure(data=[trace_2], layout=layouts)
    fig.layout.update(shapes=[
        # unfilled Rectangle
        go.layout.Shape(type="rect",
                        x0=-.7083,
                        y0=1.56,
                        x1=.7083,
                        y1=3.435,
                        line=dict(color="Black", ))
    ])
    return fig
Example #11
0
    def test_add_traces(self):

        # Add two traces
        self.figure.add_traces([go.Sankey(arrangement='snap'),
                                go.Histogram2dContour(
                                    line={'color': 'cyan'})])

        # Check access properties
        self.assertEqual(self.figure.data[-2].type, 'sankey')
        self.assertEqual(self.figure.data[-2].arrangement, 'snap')

        self.assertEqual(self.figure.data[-1].type, 'histogram2dcontour')
        self.assertEqual(self.figure.data[-1].line.color, 'cyan')

        # Check message
        new_uid1 = self.figure.data[-2].uid
        new_uid2 = self.figure.data[-1].uid
        self.figure._send_addTraces_msg.assert_called_once_with(
            [{'type': 'sankey',
              'arrangement': 'snap',
              'uid': new_uid1},
             {'type': 'histogram2dcontour',
              'line': {'color': 'cyan'},
              'uid': new_uid2}])
Example #12
0
    sns.jointplot("x", "y", data, kind='hex')

# In[21]:

sns.pairplot(data)

# In[90]:

import matplotlib.pyplot as plt
import plotly.graph_objs as go
import numpy as np
x = np.random.randn(2000)
y = np.random.randn(2000)

plt([
    go.Histogram2dContour(x=x, y=y, contours=dict(coloring='heatmap')),
    go.Scatter(x=x, y=y, mode='markers', marker=dict(color='white', size=3))
],
    show_link=False)

# In[5]:

import plotly.offline as offline
import plotly.graph_objs as go
offline.plot(
    {
        'data': [{
            'y': [14, 22, 30, 44]
        }],
        'layout': {
            'title': 'Offline Plotly',
Example #13
0
def create_contour(df,
                   title='Retweets vs. Polarity',
                   yaxis='polarity',
                   xaxes=['retweets'],
                   colors=['Blues'],
                   domains=[[[.0, .85], [.0, .85], [.85, 1.0], [.85, 1.0]]]):
    """
        This method will create contour plots for given groups of paired data.

        TODO: Figure out how to get multiple plots to work
        #colors = ['Blues', 'Reds', 'Greens']
        #domains = [
        #    [[.0, .45], [.5, .95], [.45, 0.5], [.95, 1.0]],
        #    [[.5, .95], [.5, .95], [.95, 1.0], [.95, 1.0]],
        #    [[.0, .95], [.0, .45], [.95, 1.0], [.45, 0.5]]
        #]

        Args:
            df (pandas.DataFrame): data
            yaxis (str): yaxis value
            xaxis (list): xaxis values
            domains (list): list of domain values for each trace
            colors (list): list of color scales

        Returns:
            figure dict object formatted for plotly
    """
    # Initialize data and layout lists
    data = []
    layout = {
        'showlegend': False,
        'title': title,
        'bargap': 0,
        'hovermode': 'closest'
    }
    for i in range(len(xaxes)):
        if i == 0:
            axis1_args = {
                'xaxis': {
                    'trace': 'x',
                    'layout': 'xaxis'
                },
                'yaxis': {
                    'trace': 'y',
                    'layout': 'yaxis'
                }
            }
        else:
            axis1_args = {
                'xaxis': {
                    'trace': 'x' + str(i * 2 + 1),
                    'layout': 'xaxis' + str(i * 2 + 1)
                },
                'yaxis': {
                    'trace': 'y' + str(i * 2 + 1),
                    'layout': 'yaxis' + str(i * 2 + 1)
                }
            }
        axis2_args = {
            'xaxis': {
                'trace': 'x' + str(i * 2 + 2),
                'layout': 'xaxis' + str(i * 2 + 2)
            },
            'yaxis': {
                'trace': 'y' + str(i * 2 + 2),
                'layout': 'yaxis' + str(i * 2 + 2)
            }
        }
        # Append trace values
        data.append(
            go.Histogram2dContour(x=df[xaxes[i]],
                                  y=df[yaxis],
                                  xaxis=axis1_args['xaxis']['trace'],
                                  yaxis=axis1_args['yaxis']['trace'],
                                  colorscale=colors[i],
                                  reversescale=True))
        data.append(
            go.Histogram(y=df[yaxis],
                         xaxis=axis2_args['xaxis']['trace'],
                         marker={'color': 'rgba(0,0,0,1)'}))
        data.append(
            go.Histogram(x=df[xaxes[i]],
                         yaxis=axis2_args['yaxis']['trace'],
                         marker={'color': 'rgba(0,0,0,1)'}))
        # Add layout keys
        layout[axis1_args['xaxis']['layout']] = dict(zeroline=False,
                                                     domain=domains[i][0],
                                                     showgrid=False,
                                                     title=xaxes[i])
        layout[axis1_args['yaxis']['layout']] = dict(zeroline=False,
                                                     domain=domains[i][1],
                                                     showgrid=False,
                                                     title=yaxis)
        layout[axis2_args['xaxis']['layout']] = dict(
            zeroline=False,
            domain=domains[i][2],
            showgrid=False,
        )
        layout[axis2_args['yaxis']['layout']] = dict(
            zeroline=False,
            domain=domains[i][3],
            showgrid=False,
        )

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

    return fig
Example #14
0
def update_map(slider_taxiSummaryId, hoverData):
    """ Update map 
    Data to display: 
    0: MRT Station
    1: taxi locations based on current time
    """
    #print(figure.keys())
    #layout = go.Layout(
    #        mapbox= {
    #            'accesstoken': MAPBOX_TOKEN,
    #            'center': {'lat': 1.353869, 'lon':103.817780},
    #            'zoom': 10.5,
    #
    #        },
    #       hovermode = 'closest',
    #       margin = {'l': 0, 'r': 0, 'b': 0, 't': 0}
    #)
    datasetId = slider_taxiSummaryId
    dfAllTaxi = db.selectTaxiDetailsWhereDatasetId(datasetId)

    # plot using 2D histogram contour
    x = dfAllTaxi['long']
    y = dfAllTaxi['lat']
    data = [
        go.Histogram2dContour(x=x,
                              y=y,
                              colorscale='Blues',
                              reversescale=True,
                              xaxis='x',
                              yaxis='y'),
        go.Scatter(x=x,
                   y=y,
                   xaxis='x',
                   yaxis='y',
                   mode='markers',
                   marker=dict(color='rgba(0,0,0,0.3)', size=3)),
        go.Histogram(y=y, xaxis='x2', marker=dict(color='rgba(0,0,0,1)')),
        go.Histogram(x=x, yaxis='y2', marker=dict(color='rgba(0,0,0,1)'))
    ]

    layout = go.Layout(autosize=False,
                       xaxis=dict(zeroline=False,
                                  domain=[0, 0.85],
                                  showgrid=False),
                       yaxis=dict(zeroline=False,
                                  domain=[0, 0.85],
                                  showgrid=False),
                       xaxis2=dict(zeroline=False,
                                   domain=[0.85, 1],
                                   showgrid=False),
                       yaxis2=dict(zeroline=False,
                                   domain=[0.85, 1],
                                   showgrid=False),
                       height=600,
                       width=1200,
                       bargap=0,
                       hovermode='closest',
                       showlegend=False)
    #dfNearestTaxi = db.selectNearestTaxi(1, )
    # dummy df

    #colorscale = #['rgb(255,0,0)','rgb(255,128,0)','rgb(255,255,0)','rgb(128,255,0)','rgb(0,255,0)','rgb(0,255,255)','rgb(0,128,255)',
    #                'rgb(0,0,255)', 'rgb(127,0,255)','rgb(255,0,255)','rgb(255,255,255)'   ]

    #fig = ff.create_2d_density(
    #    dfAllTaxi['long'], dfAllTaxi['lat'], colorscale=colorscale,
    #    hist_color='rgb(255, 237, 222)', point_size=3
    #)
    # go.figure is dash plot figure
    #return fig
    return go.Figure(data=data, layout=layout)
Example #15
0
def density_plot():
    '''
    Use a density plot to explore the realtionship 
    '''

    df = pd.read_csv('CSVs/city_score.csv')
    df.fillna(0, inplace=True)
    # print(df.head())

    scl = cl.scales['9']['seq']['Blues']
    colorscale = [[float(i) / float(len(scl) - 1), scl[i]]
                  for i in range(len(scl))]
    colorscale

    def kde_scipy(x, x_grid, bandwidth=0.2):
        kde = gaussian_kde(x, bw_method=bandwidth / x.std(ddof=1))
        return kde.evaluate(x_grid)

    x_grid = np.linspace(df['number'].min(), df['number'].max(), 100)
    y_grid = np.linspace(df['area'].min(), df['area'].max(), 100)

    trace1 = go.Histogram2dContour(x=df['number'],
                                   y=df['area'],
                                   name='density',
                                   ncontours=20,
                                   colorscale=colorscale,
                                   showscale=False)
    trace2 = go.Histogram(x=df['number'],
                          name='x density',
                          yaxis='y2',
                          histnorm='probability density',
                          marker=dict(color='rgb(217, 217, 217)'),
                          nbinsx=25)
    trace2s = go.Scatter(
        x=x_grid,
        y=kde_scipy(df['number'].as_matrix(), x_grid),
        yaxis='y2',
        line=dict(color='rgb(31, 119, 180)'),
        fill='tonexty',
    )
    trace3 = go.Histogram(y=df['area'],
                          name='y density',
                          xaxis='x2',
                          histnorm='probability density',
                          marker=dict(color='rgb(217, 217, 217)'),
                          nbinsy=50)
    trace3s = go.Scatter(
        y=y_grid,
        x=kde_scipy(df['area'].as_matrix(), y_grid),
        xaxis='x2',
        line=dict(color='rgb(31, 119, 180)'),
        fill='tonextx',
    )

    data = [trace1, trace2, trace2s, trace3, trace3s]

    layout = go.Layout(
        showlegend=False,
        autosize=False,
        width=700,
        height=700,
        hovermode='closest',
        bargap=0,
        xaxis=dict(domain=[0, 0.746],
                   linewidth=2,
                   linecolor='#444',
                   title='Time',
                   showgrid=False,
                   zeroline=False,
                   ticks='',
                   showline=True,
                   mirror=True),
        yaxis=dict(domain=[0, 0.746],
                   linewidth=2,
                   linecolor='#444',
                   title='Area',
                   showgrid=False,
                   zeroline=False,
                   ticks='',
                   showline=True,
                   mirror=True),
        xaxis2=dict(domain=[0.75, 1],
                    showgrid=False,
                    zeroline=False,
                    ticks='',
                    showticklabels=False),
        yaxis2=dict(domain=[0.75, 1],
                    showgrid=False,
                    zeroline=False,
                    ticks='',
                    showticklabels=False),
    )

    fig = go.Figure(data=data, layout=layout)

    url = py.plot(fig, filename='visualization/density-plot')
Example #16
0
],
                              diagonal_visible=False,
                              text=df['class'],
                              marker=dict(color=index_vals,
                                          showscale=False,
                                          line_color='white',
                                          line_width=0.5)))
fig.update_layout(title='Iris Data set', width=600, height=600)
pyo.plot(fig, filename="scatter_matrix.html")
fig.show()

# In[99]:

x = np.random.uniform(-1, 1, size=500)
y = np.random.uniform(-1, 1, size=500)
fig = go.Figure(go.Histogram2dContour(x=x, y=y, colorscale='Blues'))
pyo.plot(fig, filename="hist_contour_plot.html")
fig.show()

# In[100]:

fig = go.Figure(data=go.Contour(
    z=[[10, 10.625, 12.5, 15.625, 20], [5.625, 6.25, 8.125, 11.25, 15.625],
       [2.5, 3.125, 5., 8.125, 12.5], [0.625, 1.25, 3.125, 6.25, 10.625],
       [0, 0.625, 2.5, 5.625, 10]],
    x=[-9, -6, -5, -3, -1],  # horizontal axis
    y=[0, 1, 4, 5, 7]  # vertical axis
))
pyo.plot(fig, filename="contour_plot.html")
fig.show()
Example #17
0
def dens_plot(data,
              data_groups,
              titles,
              Dr='PCA',
              Ncols=2,
              width=1000,
              height=400):

    Distances = data['Distances']
    Centre_distances = data['centre_dists']
    fig_subplots = tools.make_subplots(rows=int(len(titles) / float(Ncols)) +
                                       (len(titles) % Ncols > 0),
                                       cols=Ncols,
                                       subplot_titles=tuple(titles))

    for pop in range(len(titles)):
        name = titles[pop]

        pos1 = int(float(pop) / Ncols) + 1
        pos2 = pop - (pos1 - 1) * Ncols + 1

        label = data_groups[pop] + 1
        print(label)

        select_l1 = [label]
        selected1 = [
            x for x in range(Distances.shape[0])
            if data[Dr]['labels_l1'][x] + 1 in select_l1
        ]

        x = np.mean(Distances[selected1, :], axis=0)
        y = np.mean(Centre_distances[selected1, :], axis=0)

        colorscale = [
            '#7A4579', '#D56073', 'rgb(236,158,105)', (1, 1, 0.2),
            (0.98, 0.98, 0.98)
        ]

        trace1 = go.Scatter(x=x,
                            y=y,
                            mode='markers',
                            name='points',
                            marker=dict(color='rgb(102,0,0)',
                                        size=5,
                                        opacity=0.4))
        trace2 = go.Histogram2dContour(x=x,
                                       y=y,
                                       name='density',
                                       ncontours=20,
                                       colorscale='Hot',
                                       reversescale=True,
                                       showscale=False)
        trace3 = go.Histogram(x=x,
                              name='x density',
                              marker=dict(color='rgb(102,0,0)'),
                              yaxis='y2')
        trace4 = go.Histogram(y=y,
                              name='y density',
                              marker=dict(color='rgb(102,0,0)'),
                              xaxis='x2')

        fig_subplots.append_trace(trace1, pos1, pos2)
        fig_subplots.append_trace(trace2, pos1, pos2)
        #fig_subplots.append_trace(trace3, pos1, pos2)
        #fig_subplots.append_trace(trace4, pos1, pos2)

        fig_subplots['layout']['yaxis' + str(pop + 1)].update(
            title='reference distances', showgrid=False, zeroline=False)

        fig_subplots['layout']['xaxis' + str(pop + 1)].update(
            title='target distances', showgrid=False, zeroline=False)

    fig_subplots['layout'].update(height=height, width=width)

    iplot(fig_subplots)
Example #18
0
    title='Distribution of Review Lengths Based on Recommendation')
fig = go.Figure(data=data, layout=layout)

iplot(fig, filename='stacked histogram')
#Recommended have lengthier reviews

#2D joint plots of rating VS Sentiment  Polarity
trace1 = go.Scatter(x=df['polarity'],
                    y=df['Rating'],
                    mode='markers',
                    name='points',
                    marker=dict(color='rgb(102,0,0)', size=2, opacity=0.4))
trace2 = go.Histogram2dContour(x=df['polarity'],
                               y=df['Rating'],
                               name='density',
                               ncontours=20,
                               colorscale='Hot',
                               reversescale=True,
                               showscale=False)
trace3 = go.Histogram(x=df['polarity'],
                      name='Sentiment polarity density',
                      marker=dict(color='rgb(102,0,0)'),
                      yaxis='y2')
trace4 = go.Histogram(y=df['Rating'],
                      name='Rating density',
                      marker=dict(color='rgb(102,0,0)'),
                      xaxis='x2')
data = [trace1, trace2, trace3, trace4]

layout = go.Layout(showlegend=False,
                   autosize=False,
def ViewportSizedHist2d(width, height):

    global prediction_df

    vw = width*45/100
    vh = height*45/100
    tw = width*0.6/100
    if width < 768:
        vw = width*80/100
        tw = width*1.5/100
    fig = go.Figure()
    fig.add_trace(go.Histogram2dContour(
            x =  prediction_df['預測鳥種數'],
            y = prediction_df['預測總隻數'],        
            colorscale = 'Greens',
            showscale =False,
            xaxis = 'x',
            yaxis = 'y',
            hoverinfo = "none",
        ))
    fig.add_trace(go.Scatter(
            x = prediction_df['預測鳥種數'],
            y = prediction_df['預測總隻數'],
            xaxis = 'x',
            yaxis = 'y',
            text = [n for n in prediction_df['名稱']],
            hoverlabel=dict(bgcolor='#000000',bordercolor='#ffffff',font=dict(size=18, color='#ffffff')),
            hovertemplate="%{text}預測,%{x}種鳥,共%{y}隻<extra></extra>", 
            mode = 'markers',
            marker = dict(
                color = '#fe7171',
                size = 3
            )
        ))
    fig.add_trace(go.Histogram(
            y = prediction_df['預測總隻數'],
            xaxis = 'x2',
            hoverinfo = "none",
            marker = dict(
                color = '#006a71'
            )
        ))
    fig.add_trace(go.Histogram(
            x = prediction_df['預測鳥種數'],
            yaxis = 'y2',
            hoverinfo = "none",
            marker = dict(
                color = '#e5df88'
            )
            
        ))

    fig.update_layout(
        autosize = False,
        xaxis = dict(zeroline = False,domain = [0,0.85],showgrid = False),
        yaxis = dict(zeroline = False,domain = [0,0.85],showgrid = False),
        xaxis2 = dict(zeroline = False,domain = [0.85,1],showgrid = False,title=dict(text='預測總鳥種數',font=dict(size=tw))),
        yaxis2 = dict(zeroline = False,domain = [0.85,1],showgrid = False,title=dict(text='預測總隻數',font=dict(size=tw))),
        bargap = 0,
        hovermode = 'closest',
        showlegend = False,
        dragmode=False,
        plot_bgcolor='rgba(0,0,0,0)',
        paper_bgcolor='rgba(0,0,0,0)',
        margin=dict(l=0,r=0,b=0,t=0),
        height = vh,
        width = vw,
    )

    return fig
Example #20
0
def KDE_plot():
    plot([go.Histogram2dContour(x=reviews.head(500)["points"],
                                 y=reviews.head(500)["price"],
                                 contours=go.Contours(coloring="heatmap")),
                                 go.Scatter(x=reviews.head(1000)["points"], y=reviews.head(1000)["price"], mode="markers")
                                 ])
                   yaxis=dict(title='Injury Severity',
                              tickmode='array',
                              automargin=True,
                              titlefont=dict(size=20)),
                   xaxis=dict(title='Hour of Day (24h)',
                              tickvals=list(range(24)),
                              titlefont=dict(size=20)))

x = df_DriversData['Crash Date/Time'].dt.hour
y = df_DriversData['Injury Severity']
trace = [
    go.Histogram2dContour(x=x,
                          y=y,
                          colorscale='Viridis',
                          contours=dict(showlabels=True,
                                        labelfont=dict(family='Raleway',
                                                       color='white')),
                          hoverlabel=dict(bgcolor='white',
                                          bordercolor='black',
                                          font=dict(family='Raleway',
                                                    color='black')))
]

fig = go.Figure(data=trace, layout=layout)
py.iplot(fig, filename="Histogram2d_Crash_Injury")

#HR vs Damage
layout = go.Layout(margin=dict(b=50, l=50),
                   yaxis=dict(title='Vehicle Damage Extent',
                              tickmode='array',
                              automargin=True,
                              titlefont=dict(size=20)),
Example #22
0
               mode='markers')
])

# This chart is fully interactive. We can use the toolbar on the top-right to perform various operations on the data: zooming and panning, for example. When we hover over a data point, we get a tooltip. We can even save the plot as a PNG image.
#
# This chart also demonstrates the *disadvantage* of this fancier plotting library. In order to keep performance reasonable, we had to limit ourselves to the first 1000 points in the dataset. While this was necessary anyway (to avoid too much overplotting) it's important to note that in general, interactive graphics are much, much more resource-intensive than static ones. It's easier to "max out" how many points of data you can show.
#
# Notice the "shape" of the `plotly` API. `iplot` takes a list of plot objects and composes them for you, plotting the combined end result. This makes it easy to stack plots.
#
# As another example, here's a KDE plot (what `plotly` refers to as a `Histogram2dContour`) *and* scatter plot of the same data.

# In[ ]:

iplot([
    go.Histogram2dContour(x=reviews.head(500)['points'],
                          y=reviews.head(500)['price'],
                          contours=go.Contours(coloring='heatmap')),
    go.Scatter(x=reviews.head(1000)['points'],
               y=reviews.head(1000)['price'],
               mode='markers')
])

# `plotly` exposes several different APIs, ranging in complexity from low-level to high-level. `iplot` is the highest-level API, and hence, the most convenient one for general-purpose use.
#
# Personally I've always found the `plotly` `Surface` its most impressive feature (albeit one of the hardest to get right):

# In[ ]:

df = reviews.assign(n=0).groupby(['points',
                                  'price'])['n'].count().reset_index()
df = df[df["price"] < 100]
Example #23
0
import plotly.graph_objs as go
import datetime
import numpy as np
from dash.dependencies import Input, Output
from apps import common
from app import app

df = pd.read_csv('data/finalInfo.csv')

features = df.pitcher_id.unique()
features.sort()
opts = [{'label': i, 'value': i} for i in features]

trace_1 = go.Histogram2dContour(x=df.px,
                                y=df.pz,
                                colorscale='Jet',
                                zmin=1,
                                zauto=False)

layouts = go.Layout(title='Pitch Location',
                    hovermode=False,
                    height=700,
                    width=700)
fig = go.Figure(data=[trace_1], layout=layouts)

layout = html.Div([
    #common.get_header(),
    #common.get_menu(),
    html.Div([
        html.H1("This is my first dashboard"),
        html.P("Dash is so interesting!!")