Python plotly.graph_objs.Figure() Examples

The following are 30 code examples of plotly.graph_objs.Figure(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module plotly.graph_objs , or try the search function .
Example #1
Source File: viz.py    From ConvLab with MIT License 7 votes vote down vote up
def plot_mean_sr(sr_list, time_sr, title, y_title, x_title):
    '''Plot a list of series using its mean, with error bar using std'''
    mean_sr, std_sr = util.calc_srs_mean_std(sr_list)
    max_sr = mean_sr + std_sr
    min_sr = mean_sr - std_sr
    max_y = max_sr.tolist()
    min_y = min_sr.tolist()
    x = time_sr.tolist()
    color = get_palette(1)[0]
    main_trace = go.Scatter(
        x=x, y=mean_sr, mode='lines', showlegend=False,
        line={'color': color, 'width': 1},
    )
    envelope_trace = go.Scatter(
        x=x + x[::-1], y=max_y + min_y[::-1], showlegend=False,
        line={'color': 'rgba(0, 0, 0, 0)'},
        fill='tozerox', fillcolor=lower_opacity(color, 0.2),
    )
    data = [main_trace, envelope_trace]
    layout = create_layout(title=title, y_title=y_title, x_title=x_title)
    fig = go.Figure(data, layout)
    return fig 
Example #2
Source File: callret_analysis.py    From idasec with GNU Lesser General Public License v2.1 7 votes vote down vote up
def generate_chart(self, _):
        try:
            import plotly
            import plotly.graph_objs as go
            data = [[0, 0, 0], [0, 0, 0]]
            ok, viol = self.results.get_ok_viol()
            x = ["OK (%d)" % ok, "Tampering (%d)" % viol]
            for ret in self.results:
                i = 1 if ret.is_tampering() else 0
                data[i][0] += ret.is_aligned()
                data[i][1] += ret.is_disaligned()
                data[i][2] += ret.is_single()
            final_data = [go.Bar(x=x, y=[x[0] for x in data], name="Aligned"), go.Bar(x=x, y=[x[1] for x in data], name="Disaligned"), go.Bar(x=x, y=[x[2] for x in data], name="Single")]
            fig = go.Figure(data=final_data, layout=go.Layout(barmode='group', title='Call stack tampering labels'))
            plotly.offline.plot(fig, output_type='file', include_plotlyjs=True, auto_open=True)
        except ImportError:
            self.log("ERROR", "Plotly module not available") 
Example #3
Source File: draw.py    From textprep with MIT License 7 votes vote down vote up
def _draw_scatter(all_vocabs, all_freqs, output_prefix):
    colors = [(s and t) and (s < t and s / t or t / s) or 0
              for s, t in all_freqs]
    colors = [c and np.log(c) or 0 for c in colors]
    trace = go.Scattergl(
        x=[s for s, t in all_freqs],
        y=[t for s, t in all_freqs],
        mode='markers',
        text=all_vocabs,
        marker=dict(color=colors, showscale=True, colorscale='Viridis'))
    layout = go.Layout(
        title='Scatter plot of shared tokens',
        hovermode='closest',
        xaxis=dict(title='src freq', type='log', autorange=True),
        yaxis=dict(title='trg freq', type='log', autorange=True))

    fig = go.Figure(data=[trace], layout=layout)
    py.plot(
        fig, filename='{}_scatter.html'.format(output_prefix), auto_open=False) 
Example #4
Source File: nanoplotter_main.py    From NanoPlot with GNU General Public License v3.0 6 votes vote down vote up
def plotly_histogram(array, color="#4CB391", title=None, xlabel=None, ylabel=None):
    data = [go.Histogram(x=array,
                         opacity=0.4,
                         marker=dict(color=color))]
    html = plotly.offline.plot(
        {"data": data,
         "layout": go.Layout(barmode='overlay',
                             title=title,
                             yaxis_title=ylabel,
                             xaxis_title=xlabel)},
        output_type="div",
        show_link=False)
    fig = go.Figure(
        {"data": data,
         "layout": go.Layout(barmode='overlay',
                             title=title)})
    return html, fig 
Example #5
Source File: peak_load_supply.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def peak_load_building(data_frame, analysis_fields, title, output_path):
    # CREATE FIRST PAGE WITH TIMESERIES
    traces = []
    area = data_frame["GFA_m2"]
    data_frame = data_frame[analysis_fields]
    x = ["Absolute [kW] ", "Relative [W/m2]"]
    for field in analysis_fields:
        y = [data_frame[field], data_frame[field] / area * 1000]
        name = NAMING[field]
        trace = go.Bar(x=x, y=y, name=name,
                       marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(images=LOGO, title=title, barmode='group', yaxis=dict(title='Peak Load'), showlegend=True)
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #6
Source File: peak_load_supply.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def peak_load_district(data_frame_totals, analysis_fields, title, output_path):
    traces = []
    data_frame_totals['total'] = data_frame_totals[analysis_fields].sum(axis=1)
    data_frame_totals = data_frame_totals.sort_values(by='total',
                                                      ascending=False)  # this will get the maximum value to the left
    for field in analysis_fields:
        y = data_frame_totals[field]
        total_perc = (y / data_frame_totals['total'] * 100).round(2).values
        total_perc_txt = ["(" + str(x) + " %)" for x in total_perc]
        name = NAMING[field]
        trace = go.Bar(x=data_frame_totals["Name"], y=y, name=name,
                       marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(title=title, barmode='group', yaxis=dict(title='Peak Load [kW]'), showlegend=True)
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #7
Source File: energy_end_use_intensity.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def energy_use_intensity_district(data_frame, analysis_fields, title, output_path):
    traces = []
    data_frame_copy = data_frame.copy()  # make a copy to avoid passing new data of the dataframe around the class
    for field in analysis_fields:
        data_frame_copy[field] = data_frame_copy[field] * 1000 / data_frame_copy["GFA_m2"]  # in kWh/m2y
        data_frame_copy['total'] = data_frame_copy[analysis_fields].sum(axis=1)
        data_frame_copy = data_frame_copy.sort_values(by='total',
                                                      ascending=False)  # this will get the maximum value to the left
    x = data_frame_copy["Name"].tolist()
    for field in analysis_fields:
        y = data_frame_copy[field]
        name = NAMING[field]
        trace = go.Bar(x=x, y=y, name=name, marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(images=LOGO, title=title, barmode='stack', yaxis=dict(title='Energy Use Intensity [kWh/m2.yr]'),
                       showlegend=True)
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #8
Source File: visualization.py    From QCPortal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def custom_plot(data: Any, layout: Any, return_figure=True) -> "plotly.Figure":
    """A custom plotly plot where the data and layout are pre-specified

    Parameters
    ----------
    data : Any
        Plotly data block
    layout : Any
        Plotly layout block
    return_figure : bool, optional
        Returns the raw plotly figure or not
    """

    check_plotly()
    import plotly.graph_objs as go

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

    return _configure_return(figure, "qcportal-bar", return_figure) 
Example #9
Source File: load_duration_curve.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def load_duration_curve(data_frame, analysis_fields, title, output_path):
    # CALCULATE GRAPH
    traces_graph = calc_graph(analysis_fields, data_frame)

    # CALCULATE TABLE
    traces_table = calc_table(analysis_fields, data_frame)

    # PLOT GRAPH

    traces_graph.append(traces_table)
    layout = go.Layout(images=LOGO, title=title, xaxis=dict(title='Duration Normalized [%]', domain=[0, 1]),
                       yaxis=dict(title='Load [kW]', domain=[0.0, 0.7]), showlegend=True)
    fig = go.Figure(data=traces_graph, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces_graph, 'layout': layout} 
Example #10
Source File: energy_balance.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def energy_balance(data_frame, analysis_fields, normalize_value, title, output_path):
    # Calculate Energy Balance
    data_frame_month = calc_monthly_energy_balance(data_frame, normalize_value)

    # CALCULATE GRAPH
    traces_graph = calc_graph(analysis_fields, data_frame_month)

    # CALCULATE TABLE
    traces_table = calc_table(data_frame_month)

    # PLOT GRAPH
    traces_graph.append(traces_table)
    layout = go.Layout(images=LOGO, title=title, barmode='relative',
                       yaxis=dict(title='Energy balance [kWh/m2_GFA]', domain=[0.35, 1.0]))
    fig = go.Figure(data=traces_graph, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces_graph, 'layout': layout} 
Example #11
Source File: b_photovoltaic_thermal_potential.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def pvt_district_monthly(data_frame, analysis_fields, title, output_path):
    E_analysis_fields_used = data_frame.columns[data_frame.columns.isin(analysis_fields[0:5])].tolist()
    Q_analysis_fields_used = data_frame.columns[data_frame.columns.isin(analysis_fields[5:10])].tolist()

    range = calc_range(data_frame, E_analysis_fields_used, Q_analysis_fields_used)
    # CALCULATE GRAPH
    traces_graphs = calc_graph(E_analysis_fields_used, Q_analysis_fields_used, data_frame)

    # CALCULATE TABLE
    traces_table = calc_table(E_analysis_fields_used, Q_analysis_fields_used, data_frame)

    # PLOT GRAPH
    traces_graphs.append(traces_table)
    layout = go.Layout(images=LOGO, title=title, barmode='stack',
                       yaxis=dict(title='PVT Electricity/Heat production [MWh]', domain=[0.35, 1], rangemode='tozero',
                                  scaleanchor='y2', range=range),
                       yaxis2=dict(overlaying='y', anchor='x', domain=[0.35, 1], range=range))

    fig = go.Figure(data=traces_graphs, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces_graphs, 'layout': layout} 
Example #12
Source File: peak_load.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def peak_load_district(data_frame_totals, analysis_fields, title, output_path):
    traces = []
    data_frame_totals['total'] = data_frame_totals[analysis_fields].sum(axis=1)
    data_frame_totals = data_frame_totals.sort_values(by='total',
                                                      ascending=False)  # this will get the maximum value to the left
    for field in analysis_fields:
        y = data_frame_totals[field]
        total_perc = (y / data_frame_totals['total'] * 100).round(2).values
        total_perc_txt = ["(" + str(x) + " %)" for x in total_perc]
        name = NAMING[field]
        trace = go.Bar(x=data_frame_totals["Name"], y=y, name=name,
                       marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(title=title, barmode='group', yaxis=dict(title='Peak Load [kW]'), showlegend=True)
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #13
Source File: peak_load.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def peak_load_building(data_frame, analysis_fields, title, output_path):
    # CREATE FIRST PAGE WITH TIMESERIES
    traces = []
    area = data_frame["GFA_m2"]
    data_frame = data_frame[analysis_fields]
    x = ["Absolute [kW] ", "Relative [W/m2]"]
    for field in analysis_fields:
        y = [data_frame[field], data_frame[field] / area * 1000]
        name = NAMING[field]
        trace = go.Bar(x=x, y=y, name=name,
                       marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(images=LOGO, title=title, barmode='group', yaxis=dict(title='Peak Load'), showlegend=True)
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #14
Source File: heating_reset_schedule.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def heating_reset_schedule(data_frame, analysis_fields, title, output_path):
    # CREATE FIRST PAGE WITH TIMESERIES
    traces = []
    x = data_frame["T_ext_C"].values
    data_frame = data_frame.replace(0, np.nan)
    for field in analysis_fields:
        y = data_frame[field].values
        name = NAMING[field]
        trace = go.Scattergl(x=x, y=y, name=name, mode='markers',
                           marker=dict(color=COLOR[field]))
        traces.append(trace)

    layout = go.Layout(images=LOGO, title=title,
                       xaxis=dict(title='Outdoor Temperature [C]'),
                       yaxis=dict(title='HVAC System Temperature [C]'))
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #15
Source File: drawer.py    From zvt with MIT License 6 votes vote down vote up
def draw_table(self, width=None, height=None, title=None, keep_ui_state=True, **kwargs):
        cols = self.main_data.data_df.index.names + self.main_data.data_df.columns.tolist()

        index1 = self.main_data.data_df.index.get_level_values(0).tolist()
        index2 = self.main_data.data_df.index.get_level_values(1).tolist()
        values = [index1] + [index2] + [self.main_data.data_df[col] for col in self.main_data.data_df.columns]

        data = go.Table(
            header=dict(values=cols,
                        fill_color=['#000080', '#000080'] + ['#0066cc'] * len(self.main_data.data_df.columns),
                        align='left',
                        font=dict(color='white', size=13)),
            cells=dict(values=values, fill=dict(color='#F5F8FF'), align='left'), **kwargs)

        fig = go.Figure()
        fig.add_traces([data])
        fig.update_layout(self.gen_plotly_layout(width=width, height=height, title=title, keep_ui_state=keep_ui_state))

        fig.show() 
Example #16
Source File: motion_capture.py    From deep-nrsfm with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_figure3d(points3d, gt=None, range_scale=1):
    """Yields plotly fig for visualization"""
    traces = get_trace3d(points3d, BLUE, BLUE, "prediction")
    if gt is not None:
        traces += get_trace3d(gt, RED, RED, "groundtruth")
    layout = go.Layout(
        scene=dict(
            aspectratio=dict(x=0.8,
                             y=0.8,
                             z=2),
            xaxis=dict(range=(-0.4 * range_scale, 0.4 * range_scale),),
            yaxis=dict(range=(-0.4 * range_scale, 0.4 * range_scale),),
            zaxis=dict(range=(-1 * range_scale, 1 * range_scale),),),
        width=700,
        margin=dict(r=20, l=10, b=10, t=10))
    return go.Figure(data=traces, layout=layout) 
Example #17
Source File: plot_plotly.py    From vslam_evaluation with MIT License 6 votes vote down vote up
def running_times():
    rospack = rospkg.RosPack()
    data_path = os.path.join(rospack.get_path('vslam_evaluation'), 'out')
    df = pd.read_csv(os.path.join(data_path, 'runtimes.txt'),
        header=None,
        index_col=0)

    bars = []

    for col_idx in df:
        this_stack = df[col_idx].dropna()
        bars.append(
            go.Bar(
                x=this_stack.index,
                y=this_stack.values,
                name='Thread {}'.format(col_idx)))

    layout = go.Layout(
        barmode='stack',
        yaxis={'title': 'Running time [s]'})

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

    url = py.plot(fig, filename='vslam_eval_run_times') 
Example #18
Source File: image.py    From PyBloqs with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, contents, plotly_kwargs=None, **kwargs):
        """
        Writes out the content as raw text or HTML.

        :param contents: Plotly graphics object figure.
        :param plotly_kwargs: Kwargs that are passed to plotly plot function.
        :param kwargs: Optional styling arguments. The `style` keyword argument has special
                       meaning in that it allows styling to be grouped as one argument.
                       It is also useful in case a styling parameter name clashes with a standard
                       block parameter.
        """
        self.resource_deps = [JScript(script_string=po.offline.get_plotlyjs(), name='plotly')]

        super(PlotlyPlotBlock, self).__init__(**kwargs)

        if not isinstance(contents, PlotlyFigure):
            raise ValueError("Expected plotly.graph_objs.graph_objs.Figure type but got %s", type(contents))

        plotly_kwargs = plotly_kwargs or {}
        prefix = "<script>if (typeof require !== 'undefined') {var Plotly=require('plotly')}</script>"
        self._contents = prefix + po.plot(contents, include_plotlyjs=False, output_type='div', **plotly_kwargs) 
Example #19
Source File: test_vis.py    From IRCLogParser with GNU General Public License v3.0 6 votes vote down vote up
def test_generate_group_bar_charts(self, mock_py):
        x_values = [
            [5.10114882, 5.0194652482, 4.9908093076],
            [4.5824497358, 4.7083614037, 4.3812775722],
            [2.6839471308, 3.0441476209, 3.6403820447]
        ]
        y_values = ['#kubuntu-devel', '#ubuntu-devel', '#kubuntu']
        trace_headers = ['head1', 'head2', 'head3']
        test_data = [
            go.Bar(
                x=x_values,
                y=y_values[i],
                name=trace_headers[i]
            ) for i in range(len(y_values))
        ]

        layout = go.Layout(barmode='group')
        fig = go.Figure(data=test_data, layout=layout)
        vis.generate_group_bar_charts(y_values, x_values, trace_headers, self.test_data_dir, 'test_group_bar_chart')
        self.assertEqual(mock_py.call_count, 1)
        self.assertEqual(fig.get('data')[0], mock_py.call_args[0][0].get('data')[0]) 
Example #20
Source File: figure.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def __init__(self, plotlyfig, colormap=None, pythonValue=None, **kwargs):
        '''
        Create a table object

        Parameters
        ----------
        plotlyfig : plotly.Figure
            The plotly figure to encapsulate

        colormap : ColorMap, optional
            A pygsti color map object used for this figure.

        pythonValue : object, optional
            A python object to be used as the Python-version of
            this figure (usually the data being plotted in some
            convenient format).

        kwargs : dict
            Additional meta-data relevant to this figure
        '''
        self.plotlyfig = plotlyfig
        self.colormap = colormap
        self.pythonvalue = pythonValue
        self.metadata = dict(kwargs).copy() 
Example #21
Source File: f_pump_duration_curve.py    From CityEnergyAnalyst with MIT License 5 votes vote down vote up
def loss_duration_curve(data_frame, analysis_fields, title, output_path):
    # CALCULATE GRAPH
    traces_graph = calc_graph(analysis_fields, data_frame)

    # CALCULATE TABLE
    traces_table = calc_table(analysis_fields, data_frame)

    # PLOT GRAPH
    traces_graph.append(traces_table)
    layout = go.Layout(images=LOGO, title=title, xaxis=dict(title='Duration Normalized [%]', domain=[0, 1]),
                       yaxis=dict(title='Load [kW]', domain=[0.0, 0.7]))
    fig = go.Figure(data=traces_graph, layout=layout)
    plot(fig, auto_open=False, filename=output_path)
    return {'data': traces_graph, 'layout': layout} 
Example #22
Source File: Swings.py    From ElliotWaveAnalysis with GNU General Public License v3.0 5 votes vote down vote up
def export_OHLC_graph(self):

        if self.update:
            print("Did update, graph is screwy")
        OHLC_trace = go.Ohlc(x=self.OHLC_data.Date_Time,
                open=self.OHLC_data.Open,
                high=self.OHLC_data.High,
                low=self.OHLC_data.Low,
                close=self.OHLC_data.Close,
                name="OHLC Data",
                increasing=dict(line=dict(color= '#408e4a')),
                decreasing=dict(line=dict(color= '#cc2718')))

        swing_data = pd.read_csv(self.swing_file, names=['Date_Time', 'Price', 'Direction', 'Row'], parse_dates=True)
        swing_trace = go.Scatter(
            x = swing_data.Date_Time,
            y = swing_data.Price,
            mode = 'lines+markers',
            name = 'Swings',
            line = dict(
                color = ('rgb(111, 126, 130)'),
                width = 3)
        )

        data = [OHLC_trace, swing_trace]

        layout = {
            'title': self.data_file[:-4],
            'yaxis': {'title': 'Price'},
        }
        fig = go.Figure(data=data, layout=layout)
        offline.plot(fig, output_type='file',filename=self.data_file + ".html", image='png', image_filename=self.data_file) 
Example #23
Source File: peak_load.py    From CityEnergyAnalyst with MIT License 5 votes vote down vote up
def diversity_factor(data_frame_timeseries, data_frame_totals, analysis_fields, title, output_path):
    traces = []
    x = ["Aggregated [MW] ", "System [MW]"]
    for field in analysis_fields:
        y1 = data_frame_totals[field + '0_kW'].sum() / 1000
        y2 = data_frame_timeseries[field + '_kWh'].max() / 1000
        y = [y1, y2]
        trace = go.Bar(x=x, y=y, name=field.split('0', 1)[0])
        traces.append(trace)

    layout = go.Layout(title=title, barmode='stack', yaxis=dict(title='Peak Load [MW]'))
    fig = go.Figure(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path) 
Example #24
Source File: Swings.py    From ElliotWaveAnalysis with GNU General Public License v3.0 5 votes vote down vote up
def graph_OHLC(self):
        #not quite there, but the other one works, which is what i really care about
        OHLC_trace = go.Ohlc(x=self.OHLC_data.Date_Time,
                open=self.OHLC_data.Open,
                high=self.OHLC_data.High,
                low=self.OHLC_data.Low,
                close=self.OHLC_data.Close,
                name="OHLC Data",
                increasing=dict(line=dict(color= '#408e4a')),
                decreasing=dict(line=dict(color= '#cc2718')))

        swing_data = pd.read_csv(self.swing_file, names=['Date_Time', 'Price', 'Direction', 'Row'], parse_dates=True)
        swing_trace = go.Scatter(
            x = swing_data.Date_Time,
            y = swing_data.Price,
            mode = 'lines+markers',
            name = 'Swings',
            line = dict(
                color = ('rgb(111, 126, 130)'),
                width = 3)
        )

        data = [OHLC_trace, swing_trace]
        layout = go.Layout(xaxis = dict(rangeslider = dict(visible = False)), title= self.data_file[:-4])

        fig = go.Figure(data=data, layout=layout)
        py.plot(fig, filename=self.data_file + ".html", output_type='file') 
Example #25
Source File: test_vis.py    From IRCLogParser with GNU General Public License v3.0 5 votes vote down vote up
def test_csv_heatmap_generator_plotly(self, mock_py):
        test_data = np.array([[5075, 507, 634, 7237, 3421, 7522, 12180, 9635, 7381, 7967, 6224, 2712, 4758, 2704, 1763,
                               1869, 4428, 1680],
                              [1652, 425, 269, 982, 2687, 15318, 3865, 3213, 4411, 6821, 1960, 7007, 883, 4592, 0, 3271,
                               619, 1508],
                              [1578, 924, 409, 1115, 6088, 491, 1923, 10700, 16206, 8690, 1350, 3778, 237, 1095, 20639,
                               2669, 1956, 6015]])

        trace = go.Heatmap(
            z=test_data,
            x=list(range(48)),
            y=list(range(1, 12)),
            colorscale=[
                [0, 'rgb(255, 255, 204)'],
                [0.13, 'rgb(255, 237, 160)'],
                [0.25, 'rgb(254, 217, 118)'],
                [0.38, 'rgb(254, 178, 76)'],
                [0.5, 'rgb(253, 141, 60)'],
                [0.63, 'rgb(252, 78, 42)'],
                [0.75, 'rgb(227, 26, 28)'],
                [0.88, 'rgb(189, 0, 38)'],
                [1.0, 'rgb(128, 0, 38)']
            ]
        )

        final_data = [trace]
        layout = go.Layout(title='HeatMap', width=800, height=640)
        fig = go.Figure(data=final_data, layout=layout)

        vis.csv_heatmap_generator_plotly(self.test_data_dir + "/vis/", self.test_data_dir, "plotly_heatmap_test")
        self.assertEqual(mock_py.call_count, 1)
        self.assertTrue(fig.get('layout') == mock_py.call_args[0][0].get('layout'))
        np.testing.assert_array_equal(fig.data[0].get('z'), mock_py.call_args[0][0].data[0].get('z')) 
Example #26
Source File: viz.py    From ConvLab with MIT License 5 votes vote down vote up
def plot_sr(sr, time_sr, title, y_title, x_title):
    '''Plot a series'''
    x = time_sr.tolist()
    color = get_palette(1)[0]
    main_trace = go.Scatter(
        x=x, y=sr, mode='lines', showlegend=False,
        line={'color': color, 'width': 1},
    )
    data = [main_trace]
    layout = create_layout(title=title, y_title=y_title, x_title=x_title)
    fig = go.Figure(data, layout)
    plot(fig)
    return fig 
Example #27
Source File: vis.py    From IRCLogParser with GNU General Public License v3.0 5 votes vote down vote up
def csv_heatmap_generator_plotly(in_directory, output_directory, output_file_name):
    """
        Plots heatmaps for all the csv files in the given directory

    Args:
        in_directory (str):  location of input csv files
        output_drectory(str): location to save graph
        output_file_name(str): name of the image file to be saved

    Returns:
        null
    """

    file_list = glob.glob(in_directory+"*.csv")

    for file in file_list:
        csv_data = genfromtxt(file, delimiter=',')

        trace = go.Heatmap(
                z=csv_data,
                x=list(range(48)),
                y=list(range(1, 12)),
                colorscale=[
                [0, 'rgb(255, 255, 204)'],
                [0.13, 'rgb(255, 237, 160)'],
                [0.25, 'rgb(254, 217, 118)'],
                [0.38, 'rgb(254, 178, 76)'],
                [0.5, 'rgb(253, 141, 60)'],
                [0.63, 'rgb(252, 78, 42)'],
                [0.75, 'rgb(227, 26, 28)'],
                [0.88, 'rgb(189, 0, 38)'],
                [1.0, 'rgb(128, 0, 38)']
            ]
        )

        data = [trace]
        layout = go.Layout(title='HeatMap', width=800, height=640)
        fig = go.Figure(data=data, layout=layout)

        py.image.save_as(fig, filename=in_directory+file[file.rfind("/")+1:-4]+'_heatmap.png') 
Example #28
Source File: test_image.py    From PyBloqs with GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_plotlyplot():
    x = np.array([2, 5, 8, 0, 2, -8, 4, 3, 1])
    y = np.array([2, 5, 8, 0, 2, -8, 4, 3, 1])

    data = [go.Scatter(x=x, y=y)]
    fig = go.Figure(data=data, layout=go.Layout(title='Offline Plotly Testing', width=800, height=500,
                                                xaxis=dict(title='X-axis'), yaxis=dict(title='Y-axis')))

    return PlotlyPlotBlock(fig) 
Example #29
Source File: test_image_unit.py    From PyBloqs with GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_pass_on_plotly_kwargs():
    fig = go.Figure()
    with patch('plotly.offline.plot') as pl:
        i.PlotlyPlotBlock(fig, plotly_kwargs={'a': 'B'})
    assert pl.call_args[1]['a'] == 'B' 
Example #30
Source File: pycoQC_plot.py    From pycoQC with GNU General Public License v3.0 5 votes vote down vote up
def __summary_plot (self, width, height, plot_title, header, data_format, data):
        """Private function generating summary table plots"""
        self.logger.info ("\t\tComputing plot")

        # Plot data
        data = [go.Table(
            header = {
                "values":header,
                "align":"center", "fill":{"color":"grey"},
                "font":{"size":14, "color":"white"},
                "height":40},
            cells = {
                "values":data,
                "format": data_format,
                "align":"center",
                "fill":{"color":"whitesmoke"},
                "font":{"size":12}, "height":30})]

        # tweak plot layout
        layout = go.Layout (
            width = width,
            height = height,
            title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"})

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

    #~~~~~~~1D DISTRIBUTION METHODS AND HELPER~~~~~~~#