How to use the plotly.graph_objs.Bar function in plotly

To help you get started, we’ve selected a few plotly examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ShorensteinCenter / Benchmarks-Program / app / visualizations.py View on Github external
y_vals: a list containing the bar y-values
        diff_vals difference between monthly values (for labels), if the
            previous month's data is included.
        title: the chart title.
        filename: the filename of the exported png.
        percentage_values: if true, formats y-values as percentages.
    """
    label_text = [
        '{:.1%}'.format(y_val) if percentage_values
        else '{:,d}'.format(int(y_val))
        for y_val in y_vals]
    if diff_vals:
        label_text[1] += ('<br>(' + diff_vals[0] + ')')
        label_text[3] += ('<br>(' + diff_vals[1] + ')')

    trace = go.Bar(
        x=x_vals,
        y=y_vals,
        width=[0.6 for x_val in x_vals],
        text=label_text,
        textposition='outside',
        cliponaxis=False,
        marker={'color': (
            [FILL_COLORS[0], FILL_COLORS[0], FILL_COLORS[1], FILL_COLORS[1]]
            if diff_vals
            else [FILL_COLORS[0], FILL_COLORS[1]])}
    )
    data = [trace]
    layout = go.Layout(
        title=title,
        autosize=False,
        width=600,
github cdubz / babybuddy / reports / graphs.py View on Github external
start_date,
            duration.seconds/60,
            'Asleep {} ({} to {})'.format(
                duration_string(duration),
                start_time.strftime('%I:%M %p'),
                end_time.strftime('%I:%M %p')
            )
        )

        last_end_time = end_time

    dates = list(y_df)
    traces = []
    color = 'rgba(255, 255, 255, 0)'
    for index, row in y_df.iterrows():
        traces.append(go.Bar(
            x=dates,
            y=row,
            text=text_df.ix[index],
            hoverinfo='text',
            marker={'color': color},
            showlegend=False,
        ))
        if color == 'rgba(255, 255, 255, 0)':
            color = 'rgb(35, 110, 150)'
        else:
            color = 'rgba(255, 255, 255, 0)'

    layout_args = utils.default_graph_layout_options()
    layout_args['margin']['b'] = 100

    layout_args['barmode'] = 'stack'
github XAI-ANITI / ethik / ethik / base_explainer.py View on Github external
if type(colors) is dict:
            # Put the colors in the right order
            colors = [colors.get(feature) for feature in features]

        width = 500
        height = 100 + 60 * len(features)
        if size is not None:
            width, height = size

        reference_name = reference_name or '"reference"'
        compared_name = compared_name or '"compared"'
        title = f"{title_prefix} for {compared_name} compared to {reference_name}"

        fig = go.Figure()
        fig.add_trace(
            go.Bar(
                x=comparison["delta"],
                y=features,
                orientation="h",
                hoverinfo="x",
                marker=dict(color=colors),
            )
        )
        fig.update_layout(
            xaxis=dict(title=title, range=yrange, side="top", fixedrange=True),
            yaxis=dict(showline=False, automargin=True),
            shapes=[
                go.layout.Shape(
                    type="line",
                    x0=0,
                    y0=0,
                    x1=0,
github rsemeraro / PyPore / lib / alg_routines_unix.py View on Github external
def plot_stats(out_dict, s_unmap, s_map, c_c_dict, odir, oredered_contigs):
    fig = tools.make_subplots(rows=3, cols=2, specs=[[{}, {}], [{'colspan': 2}, None], [{'colspan': 2}, None]],
                              shared_xaxes=False,
                              shared_yaxes=False, vertical_spacing=0.1, print_grid=False)

    trace1 = go.Bar(
        x=map(lambda x: x[1], s_map),
        y=map(lambda x: '_' + str(x[0]), s_map),
        name='Mapped',
        orientation='h',
        showlegend=True,
        visible=True,
        text=map(lambda x: str(x[1]), s_map),
        marker=dict(color='rgba(50, 171, 96, 0.6)',
                    line=dict(
                        color='rgba(50, 171, 96, 1.0)',
                        width=0.3)),
        hoverinfo="text+name"
    )
    fig.append_trace(trace1, 1, 1)
    trace2 = go.Bar(
        x=map(lambda x: x[2], s_map),
github phenomecentre / nPYc-Toolbox / nPYc / plotting / _multivariatePlotting.py View on Github external
)

			data.append(LOADSplot)
			xReverse = True
			Xlabel = 'Retention Time'
			Ylabel = 'm/z'


		# For NMR data
		elif hasattr(featureMetadata, 'ppm'):

			Xvals = featureMetadata['ppm']
			hovertext = ["ppm: %.4f; W: %s" % i for i in zip(featureMetadata['ppm'], W_str)] # Text for tooltips

			# Bar starts at minimum spectral intensity
			LOADSmin = go.Bar(
				x = Xvals,
				y = numpy.min(dataMasked.intensityData, axis=0),
	#			y = numpy.percentile(PCAmodel.intensityData, 1, axis=0),
				marker = dict(
					color = 'white'
					),
				hoverinfo = 'skip',
				showlegend = False
				)

			# Bar ends at maximum spectral intensity, bar for each feature coloured by loadings weight
			LOADSmax = go.Bar(
				x = Xvals,
				y = numpy.max(dataMasked.intensityData, axis=0),
	#			y = numpy.percentile(PCAmodel.intensityData, 99, axis=0),
				marker = dict(
github zvtvz / zvt / zvt / drawer / drawer.py View on Github external
if subplot:
                # 绘制幅图
                sub_df = self.sub_data.entity_map_df.get(entity_id)
                if pd_is_not_null(sub_df):
                    for col in sub_df.columns:
                        trace_name = '{}_{}'.format(code, col)
                        ydata = sub_df[col].values.tolist()

                        def color(i):
                            if i > 0:
                                return 'red'
                            else:
                                return 'green'

                        colors = [color(i) for i in ydata]
                        bar = go.Bar(x=sub_df.index, y=ydata, name=trace_name, yaxis='y2', marker_color=colors)
                        sub_traces.append(bar)

        if subplot:
            fig.add_traces(traces, rows=[1] * len(traces), cols=[1] * len(traces))
            fig.add_traces(sub_traces, rows=[2] * len(sub_traces), cols=[1] * len(sub_traces))
        else:
            fig.add_traces(traces)

        fig.update_layout(self.gen_plotly_layout(width=width, height=height, title=title, keep_ui_state=keep_ui_state,
                                                 subplot=subplot))

        fig.show()
github tyiannak / multimodalAnalysis / audio / utilities.py View on Github external
def plotly_classification_results(cm, class_names):
    heatmap = go.Heatmap(z=np.flip(cm, axis=0), x=class_names,
                         y=list(reversed(class_names)),
                         colorscale=[[0, '#4422ff'], [1, '#ff4422']],
                         name="confusin matrix", showscale=False)
    rec, pre, f1 = compute_class_rec_pre_f1(cm)
    mark_prop1 = dict(color='rgba(150, 180, 80, 0.5)',
                      line=dict(color='rgba(150, 180, 80, 1)', width=2))
    mark_prop2 = dict(color='rgba(140, 200, 120, 0.5)',
                      line=dict(color='rgba(140, 200, 120, 1)', width=2))
    mark_prop3 = dict(color='rgba(50, 150, 220, 0.5)',
                      line=dict(color='rgba(50, 150, 220, 1)', width=3))
    b1 = go.Bar(x=class_names,  y=rec, name="rec", marker=mark_prop1)
    b2 = go.Bar(x=class_names,  y=pre, name="pre", marker=mark_prop2)
    b3 = go.Bar(x=class_names,  y=f1, name="f1", marker=mark_prop3)
    figs = plotly.subplots.make_subplots(rows=1, cols=2,
                                      subplot_titles=["Confusion matrix",
                                                      "Performance measures"])
    figs.append_trace(heatmap, 1, 1); figs.append_trace(b1, 1, 2)
    figs.append_trace(b2, 1, 2); figs.append_trace(b3, 1, 2)
    plotly.offline.plot(figs, filename="temp.html", auto_open=True)
github guenthermi / postgres-word2vec / evaluation / evaluation_utils.py View on Github external
def plot_bars(measured_data, iplot=False, layout=None):
    data = []
    data = [go.Bar(
            x=list(measured_data.keys()),
            y=[np.mean(measured_data[x]) for x in measured_data.keys()],
            text=[np.mean(measured_data[x]) for x in measured_data.keys()],
            textposition = 'outside',
            textfont=dict(family='Arial', size=20),
    )]
    if layout == None:
        layout = go.Layout(yaxis= dict(title='time in seconds', titlefont=dict(size=30), tickfont=dict(size=30)), xaxis=dict(titlefont=dict(size=30), tickfont=dict(size=30)))
    fig = go.Figure(data=data, layout=layout)
    if iplot:
        plotly.offline.iplot(fig, filename="tmp.html")
    else:
        plotly.offline.plot(fig, filename="tmp.html", auto_open=True)
    return None
github rsemeraro / PyPore / lib / seq_routines.py View on Github external
def Bargen(PassReads, FailReads):
    trace1 = go.Bar(
        x=[FailReads],
        y=['Fail/Pass'],
        width=[0.4],
        name='Fail',
        text=str(FailReads) + "% Fail",
        orientation='h',
        showlegend=False,
        visible=False,
        hoverinfo="text",
        marker=dict(color='rgba(133, 37, 25, 1.0)'),
        xaxis='x4',
        yaxis='y4'
    )
    trace2 = go.Bar(
        x=[PassReads],
        y=['Fail/Pass'],
        width=[0.4],
        name='Pass',
        text=str(PassReads) + '% Pass',
        orientation='h',
        showlegend=False,
        visible=False,
        hoverinfo="text",
        marker=dict(color='rgba(25, 133, 37, 1.0)'),
        xaxis='x4',
        yaxis='y4'
    )
    bardata = [trace1, trace2]
    return bardata
github cdubz / babybuddy / reports / graphs / sleep_pattern.py View on Github external
)

        # Update the previous entry duration if an offset change occurred.
        # This can happen when an entry crosses a daylight savings time change.
        if start_time.utcoffset() != end_time.utcoffset():
            diff = start_time.utcoffset() - end_time.utcoffset()
            duration -= timezone.timedelta(seconds=diff.seconds)
            y_df.at[df_index - 1, start_date] = duration.seconds/60

        last_end_time = end_time

    dates = list(y_df)
    traces = []
    color = 'rgba(255, 255, 255, 0)'
    for index, row in y_df.iterrows():
        traces.append(go.Bar(
            x=dates,
            y=row,
            text=text_df.iloc[index],
            hoverinfo='text',
            marker={'color': color},
            showlegend=False,
        ))
        if color == 'rgba(255, 255, 255, 0)':
            color = 'rgb(35, 110, 150)'
        else:
            color = 'rgba(255, 255, 255, 0)'

    layout_args = utils.default_graph_layout_options()
    layout_args['margin']['b'] = 100

    layout_args['barmode'] = 'stack'