Python plotly.offline.plot() Examples

The following are 30 code examples of plotly.offline.plot(). 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.offline , or try the search function .
Example #1
Source File: backtest.py    From CoinTK with MIT License 8 votes vote down vote up
def plot_results(results, plot_name='temp-plot.html'):
    '''
        results is a list of dictionaries, each of which defines a trace
         e.g. [{'x': x_data, 'y': y_data, 'name': 'plot_name'}, {...}, {...}]

        Each dictionary's key-value pairs will be passed into go.Scatter
         to generate a trace on the graph

    '''
    traces = []

    for input_args in results:
        traces.append(go.Scatter(**input_args))

    layout = go.Layout(
        title='Trading performance over time',
        yaxis=dict(
            title='Value (USD)'
        ),
    )
    plot(go.Figure(data=traces, layout=layout), filename=plot_name) 
Example #2
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 #3
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 #4
Source File: d_energy_loss_bar.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def calc_graph(self):
        # calculate graph
        graph = []
        # format demand values
        P_loss_kWh = self.P_loss_kWh.fillna(value=0)
        P_loss_kWh = pd.DataFrame(P_loss_kWh.sum(axis=0), columns=['P_loss_kWh'])
        Q_loss_kWh = abs(self.thermal_loss_edges_kWh.fillna(value=0))
        Q_loss_kWh = pd.DataFrame(Q_loss_kWh.sum(axis=0), columns=['Q_loss_kWh'])
        # calculate total_df
        total_df = pd.DataFrame(P_loss_kWh.values + Q_loss_kWh.values, index=Q_loss_kWh.index, columns=['total'])
        # join dataframes
        merged_df = P_loss_kWh.join(Q_loss_kWh).join(total_df)
        merged_df = merged_df.sort_values(by='total',
                                          ascending=False)  # this will get the maximum value to the left

        # iterate through P_loss_kWh to plot
        for field in ['P_loss_kWh', 'Q_loss_kWh']:
            total_percent = (merged_df[field] / merged_df['total'] * 100).round(2)
            total_percent_txt = ["(" + str(x) + " %)" for x in total_percent]
            trace = go.Bar(x=merged_df.index, y=merged_df[field].values, name=NAMING[field],
                           text=total_percent_txt,
                           orientation='v',
                           marker=dict(color=COLOR[field]))
            graph.append(trace)
        return graph 
Example #5
Source File: plot.py    From sound_field_analysis-py with MIT License 6 votes vote down vote up
def plot2D(data, title=None, viz_type=None, fs=44100, line_names=None):
    """Visualize 2D data using plotly.

    Parameters
    ----------
    data : array_like
        Data to be plotted, separated along the first dimension (rows)
    title : str, optional
        Add title to be displayed on plot
    viz_type : str{None, 'Time', 'ETC', 'LinFFT', 'LogFFT'}, optional
        Type of data to be displayed [Default: None]
    fs : int, optional
        Sampling rate in Hz [Default: 44100]
    line_names : list of str, optional
        Add legend to be displayed on plot, with one entry for each data row [Default: None]
    """
    viz_type = viz_type.strip().upper()  # remove whitespaces and make upper case

    layout = layout_2D(viz_type=viz_type, title=title)
    # noinspection PyTypeChecker
    traces = prepare_2D_traces(data=data, viz_type=viz_type, fs=fs, line_names=line_names)

    showTrace(traces, layout=layout, title=title) 
Example #6
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 #7
Source File: task_plots.py    From parsl with Apache License 2.0 6 votes vote down vote up
def time_series_memory_per_task_plot(df_resources, resource_type, label):
    if resource_type == "psutil_process_memory_percent":
        yaxis = dict(title="Memory utilization")
        data = [go.Scatter(x=df_resources['timestamp'],
                           y=df_resources[resource_type])]
    else:
        yaxis = dict(title='Memory usage (GB)')
        data = [go.Scatter(x=df_resources['timestamp'],
                           y=[num / 1000000000 for num in df_resources[resource_type].astype(float)])]
    fig = go.Figure(data=data,
                    layout=go.Layout(xaxis=dict(tickformat='%m-%d\n%H:%M:%S',
                                                autorange=True,
                                                title='Time'),
                                     yaxis=yaxis,
                                     title=label))
    return plot(fig, show_link=False, output_type="div", include_plotlyjs=False) 
Example #8
Source File: image.py    From PyBloqs with GNU Lesser General Public License v2.1 6 votes vote down vote up
def set_plot_format(plot_format=None, plot_dpi=None):
    """
    Overwrite the current plot format settings

    :param plot_format: The plot format (e.g. 'png')
    :type  plot_format: str
    :param plot_dpi:    The DPI of the plots
    :type  plot_dpi:    int
    """
    global _PLOT_FORMAT
    global _PLOT_MIME_TYPE
    global _PLOT_DPI
    if plot_format is not None:
        _PLOT_FORMAT = plot_format
        _PLOT_MIME_TYPE = _MIME_TYPES[plot_format]

    if plot_dpi is not None:
        _PLOT_DPI = plot_dpi 
Example #9
Source File: e_heating_reset_curve.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def supply_return_ambient_temp_plot(data_frame, data_frame_2, analysis_fields, title, output_path):
    traces = []
    for field in analysis_fields:
        y = data_frame[field].values
        # sort by ambient temperature, needs some helper variables
        y_old = np.vstack((np.array(data_frame_2.values.T), y))
        y_new = np.vstack((np.array(data_frame_2.values.T), y))
        y_new[0, :] = y_old[0, :][
            y_old[0, :].argsort()]  # y_old[0, :] is the ambient temperature which we are sorting by
        y_new[1, :] = y_old[1, :][y_old[0, :].argsort()]
        trace = go.Scattergl(x=y_new[0], y=y_new[1], name=NAMING[field],
                           marker=dict(color=COLOR[field]),
                           mode='markers')
        traces.append(trace)

    # CREATE FIRST PAGE WITH TIMESERIES
    layout = dict(images=LOGO, title=title, yaxis=dict(title='Temperature [deg C]'),
                  xaxis=dict(title='Ambient Temperature [deg C]'))

    fig = dict(data=traces, layout=layout)
    plot(fig, auto_open=False, filename=output_path)

    return {'data': traces, 'layout': layout} 
Example #10
Source File: utils.py    From word-mesh with MIT License 6 votes vote down vote up
def save_wordmesh_as_html(self, coordinates, filename='temp-plot.html', 
                              animate=False, autozoom=True, notebook_mode=False):

        zoom = 1
        labels = ['default label']
        traces = []
        if animate:
            for i in range(coordinates.shape[0]):
                
                traces.append(self._get_trace(coordinates[i]))
                labels = list(map(str,range(coordinates.shape[0])))
                
        else:

            if autozoom:
                zoom = self._get_zoom(coordinates)
            traces = [self._get_trace(coordinates, zoom=zoom)]
            
        layout = self._get_layout(labels, zoom=zoom)
            
        fig = self.generate_figure(traces, labels, layout)
        
        if notebook_mode:
            py.init_notebook_mode(connected=True)
            py.iplot(fig, filename=filename, show_link=False)
        else:
            py.plot(fig, filename=filename, auto_open=False, show_link=False) 
Example #11
Source File: generate_labels.py    From LSTM-Crypto-Price-Prediction with MIT License 6 votes vote down vote up
def graph(self):
        # graph the labels
        trace0 = go.Scatter(y=self.hist, name='Price')
        trace1 = go.Scatter(y=self.savgol, name='Filter')
        trace2 = go.Scatter(y=self.savgol_deriv, name='Derivative', yaxis='y2')
        data = [trace0, trace1, trace2]

        layout = go.Layout(
            title='Labels',
            yaxis=dict(
                title='USDT value'
            ),
            yaxis2=dict(
                title='Derivative of Filter',
                overlaying='y',
                side='right'
            )
        )
        fig = go.Figure(data=data, layout=layout)
        py.plot(fig, filename='../docs/label.html') 
Example #12
Source File: energy_end_use.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def main():
    import cea.config
    import cea.inputlocator
    config = cea.config.Configuration()
    locator = cea.inputlocator.InputLocator(config.scenario)
    # cache = cea.plots.cache.PlotCache(config.project)
    cache = cea.plots.cache.NullPlotCache()
    EnergyDemandDistrictPlot(config.project, {'buildings': None,
                                              'scenario-name': config.scenario_name},
                             cache).plot(auto_open=True)
    EnergyDemandDistrictPlot(config.project, {'buildings': locator.get_zone_building_names()[0:2],
                                              'scenario-name': config.scenario_name},
                             cache).plot(auto_open=True)
    EnergyDemandDistrictPlot(config.project, {'buildings': [locator.get_zone_building_names()[0]],
                                              'scenario-name': config.scenario_name},
                             cache).plot(auto_open=True) 
Example #13
Source File: plotting.py    From pycls with MIT License 6 votes vote down vote up
def plot_error_curves_pyplot(log_files, names, filename=None, metric="top1_err"):
    """Plot error curves using matplotlib.pyplot and save to file."""
    plot_data = prepare_plot_data(log_files, names, metric)
    colors = get_plot_colors(len(names))
    for ind, d in enumerate(plot_data):
        c, lbl = colors[ind], d["test_label"]
        plt.plot(d["x_train"], d["y_train"], "--", c=c, alpha=0.8)
        plt.plot(d["x_test"], d["y_test"], "-", c=c, alpha=0.8, label=lbl)
    plt.title(metric + " vs. epoch\n[dash=train, solid=test]", fontsize=14)
    plt.xlabel("epoch", fontsize=14)
    plt.ylabel(metric, fontsize=14)
    plt.grid(alpha=0.4)
    plt.legend()
    if filename:
        plt.savefig(filename)
        plt.clf()
    else:
        plt.show() 
Example #14
Source File: cacheGraph.py    From nanoBench with GNU Affero General Public License v3.0 5 votes vote down vote up
def getPlotlyGraphDiv(title, x_title, y_title, traces):
   fig = go.Figure()
   fig.update_layout(title_text=title)
   fig.update_xaxes(title_text=x_title)
   fig.update_yaxes(title_text=y_title)

   for name, y_values in traces:
      fig.add_trace(go.Scatter(y=y_values, mode='lines+markers', name=name))

   return plot(fig, include_plotlyjs=False, output_type='div') 
Example #15
Source File: image.py    From PyBloqs with GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_plot_format():
    """
    Get the current plot format parameters

    :return: tuple of format and dpi
    """
    return _PLOT_FORMAT, _PLOT_DPI 
Example #16
Source File: plot.py    From sound_field_analysis-py with MIT License 5 votes vote down vote up
def plot3Dgrid(rows, cols, viz_data, style, normalize=True, title=None):
    if len(viz_data) > rows * cols:
        raise ValueError('Number of plot data is more than the specified rows and columns.')
    fig = subplots.make_subplots(rows, cols, specs=[[{'is_3d': True}] * cols] * rows, print_grid=False)

    if style == 'flat':
        layout_3D = dict(
            xaxis=dict(range=[0, 360]),
            yaxis=dict(range=[0, 181]),
            aspectmode='manual',
            aspectratio=dict(x=3.6, y=1.81, z=1)
        )
    else:
        layout_3D = dict(
            xaxis=dict(range=[-1, 1]),
            yaxis=dict(range=[-1, 1]),
            zaxis=dict(range=[-1, 1]),
            aspectmode='cube'
        )

    rows, cols = _np.mgrid[1:rows + 1, 1: cols + 1]
    rows = rows.flatten()
    cols = cols.flatten()
    for IDX in range(0, len(viz_data)):
        cur_row = int(rows[IDX])
        cur_col = int(cols[IDX])
        fig.add_trace(genVisual(viz_data[IDX], style=style, normalize=normalize), cur_row, cur_col)
        fig.layout[f'scene{IDX + 1:d}'].update(layout_3D)

    if title is not None:
        fig.layout.update(title=title)
        filename = f'{title}.html'
    else:
        filename = f'{current_time()}.html'

    if env_info() == 'jupyter_notebook':
        plotly_off.iplot(fig)
    else:
        plotly_off.plot(fig, filename=filename) 
Example #17
Source File: utils.py    From word-mesh with MIT License 5 votes vote down vote up
def __init__(self, words, fontsizes_norm, height, width, 
                 filename='temp-plot.html', title=None, textcolors='white',
                 hovertext=None, axis_visible=False, bg_color='black', 
                 title_fontcolor='white', title_fontsize='auto', 
                 title_font_family='Courier New, monospace', bb_padding=0.08,
                 boundary_padding_factor=1.1):
        
        """
        Parameters
        ----------
        """
        self.words = words
        self.fontsizes_norm = fontsizes_norm
        self.height = height
        self.width = width
        self.title = title
        self.textcolors = textcolors
        self.hovertext = hovertext
        self.axis_visible = axis_visible
        self.bg_color = bg_color
        self.title_fontcolor = title_fontcolor
        self.title_fontsize = title_fontsize
        self.title_font_family = title_font_family
        self.padding = bb_padding
        self.boundary_padding = boundary_padding_factor
        self.bounding_box_dimensions, self.real_fontsizes = self.get_bb_dimensions()
        
# fontsize*FONTSIZE_BBW = Width of the bounding box of each character in a plotly graph 
Example #18
Source File: plot_structure.py    From RAD_Tools with GNU General Public License v3.0 5 votes vote down vote up
def html_creator(plot_div, output_file):

    fh = open(output_file + ".html", "w")

    template = """
<html><head><meta charset="utf-8" /></head><body>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="htmlwidget_container">
<input id="inputText" value></input>
<button id="buttonSearch">
Search
</button>
<script>document.getElementById("buttonSearch").addEventListener("click", function()
  {
    var i = 0;
    var j = 0;
    var found = [];
    var myDiv = document.getElementsByClassName("xtick")
    for (i = 0; i < myDiv.length; i++) {
    	myDiv[i].style.fontWeight = "normal";
    	myDiv[i].childNodes[0].style.fill = "black";

    	if (document.getElementById("inputText").value !== "" && myDiv[i].textContent.indexOf(document.getElementById("inputText").value) !== -1) {
    		myDiv[i].style.fontWeight = "bold";
    		myDiv[i].childNodes[0].style.fill = "red";
    	}
    }
    Plotly.Fx.hover(myDiv, found);
  }
);</script>
</div>
%s
</body></html>
    """ % plot_div

    fh.write(template) 
Example #19
Source File: driverlessCityProject_spatialPointsPattern_association_corr.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def multiPolygonShow(lst):
    cmap = plt.cm.get_cmap('RdPu') #'Spectral'  https://matplotlib.org/2.0.1/users/colormaps.html
    fig, axs = plt.subplots(figsize=(20,20))
    axs.set_aspect('equal', 'datalim')
    i=0
    for geom in multiSegs.geoms:
        xs, ys = geom.exterior.xy 
        axs.fill(xs, ys, alpha=0.5, fc=cmap(lst[i]), ec='none')
        # axs.text(10)
        i+=1
        # if i==10:break
    # cax = plt.axes(lst)
    # plt.colorbar(cax=cax)    
    plt.show() 
    
    # What will be the angle of each axis in the plot? (we divide the plot / number of variable)
    values=lst
    values += values[:1]    
    print(len(values),len(lst))

    N=len(lst)-1
    angles = [n / float(N) * 2 * math.pi for n in range(N)]
    angles += angles[:1]
    # Initialise the spider plot
    ax = plt.subplot(111, polar=True)     
    # Draw one axe per variable + add labels labels yet
    plt.xticks(angles[:-1], list(range(num)), color='grey', size=8)     
    # Draw ylabels
    ax.set_rlabel_position(0)
    plt.yticks([0,0.5,1], ["0","0.5","1"], color="grey", size=7)
    plt.ylim(0,1)     
    # Plot data
    ax.plot(angles, values, linewidth=1, linestyle='solid')     
    # Fill area
    ax.fill(angles, values, 'b', alpha=0.1)
#auxiliary tool 
Example #20
Source File: driverlessCityProject_spatialPointsPattern_association_corr.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def quadratCount(targetPts_epoch,locationsPts_epoch,nx,ny):
    # corners=[Point(p.x+30,p.y+30),Point(p.x+30,p.y-30),Point(p.x-30,p.y-30),Point(p.x-30,p.y+30)]
    corners_coordi=[(locationsPts_epoch.x+30,locationsPts_epoch.y+30),(locationsPts_epoch.x+30,locationsPts_epoch.y-30),(locationsPts_epoch.x-30,locationsPts_epoch.y-30),(locationsPts_epoch.x-30,locationsPts_epoch.y+30)]
    target_pts=[coordinate.coords[:][0] for coordinate in targetPts_epoch]+corners_coordi
    pp = PointPattern(target_pts)
    # print("^"*50)
 
    #应用PySAL的Quadrat_statistics样方统计,亦可以替换用R的spatstat库实现,获取更多功能。参考:https://pointpats.readthedocs.io/en/latest/  https://pysal.org/notebooks/explore/pointpats/Quadrat_statistics.html
    #样方分析(Quadrat Analysis ,QA )法是样方内点数均值变差的分析方法,是由Greig-Smith 于1964年提出的。其具体做法是用一组样方覆盖在研究区域上并作叠置分析,统计落在每一个样方上的样本数,通过统计不同的具有m 个点数的样方的个数及其频率,并与完全随机过程(Poisson 分布)对比来判断点模式的空间分布特征。其结果一般用方差均值比(V ariance-Mean Ratio ,VMR )判断。
    #合理地确定样方的大小较为重要,一般地样方大小的确定采用符合“拇指规则(rule of thumb )”,即样方大小应当是平均每个点所占面积的两倍. ref:《黄土丘陵沟壑区农村居民点分布模式空间统计分析——以甘谷县为例》
    q_r = qs.QStatistic(pp,shape= "rectangle",nx = nx, ny = ny)
    # q_r.plot()
    mr=q_r.mr    
    quadratCount=mr.point_location_sta()
    # print(quadratCount)
    chi2=q_r.chi2 #观察点模式的卡方检验统计量 chi-squared test statistic for the observed point pattern
    chi2_pvalue=q_r.chi2_pvalue
    df=q_r.df
    
    comparisonValue=1
    quadratNum=sum(np.array(list(quadratCount.values()))>=comparisonValue) #the amount of the occupied quadrat based on a value used for comparison 
    
    # print(sum(np.array(list(quadratCount.values()))>=1))
    numDivQuad=len(targetPts_epoch)/sum(np.array(list(quadratCount.values()))>=1) #amount_landmarks/amount_the occupied quadrat
    return chi2,quadratNum,numDivQuad    
    
#merge all indicators 
Example #21
Source File: driverlessCityProject_spatialPointsPattern_association_corr.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def correlation_graph(df,xlabel_str,title_str):
    plt.clf()
    corr =df.corr() 
    # print("_"*50,"correlation:")
    # print(corr)
    
    #01-correlation heatmap
    sns.set()
    f, ax = plt.subplots(figsize=(10*4.5, 10*4.5))
    sns.heatmap(corr, annot=True, fmt=".2f", linewidths=.5, ax=ax)
    
    #02-bar plot
    indicatorName=corr.columns.to_numpy()
    # plt.clf()
    plt.rcdefaults()
    plt.rcParams.update({'font.size':14})
    fig, ax = plt.subplots(figsize=(10*2, 10*2))  
    y_pos = np.arange(len(indicatorName))
    error = np.random.rand(len(indicatorName))
    
    ax.barh(y_pos, corr.PHMI.to_numpy(), align='center') #xerr=error, 
    ax.set_yticks(y_pos)
    ax.set_yticklabels(indicatorName)
    ax.invert_yaxis()  # labels read top-to-bottom
    ax.set_xlabel(xlabel_str)
    ax.set_title(title_str)
    for index, value in enumerate(corr.PHMI.to_numpy()):
        plt.text(value, index, str(round(value,2)))
    plt.show()
    
    return corr

#plot multiple curve 
Example #22
Source File: test_plot.py    From MegaQC with GNU General Public License v3.0 5 votes vote down vote up
def test_get_trend_series(db, client):
    # Create 5 reports each with 1 sample. Each has a single field called 'test_field'
    data_type = factories.SampleDataTypeFactory()
    report = factories.ReportFactory.create_batch(5, samples__data__data_type=data_type)
    db.session.add_all(report)
    db.session.commit()

    # plots = jpi.get('plots/trends/series')
    url = url_for(
        "rest_api.trend_data",
        **{
            "filter": json.dumps([]),
            "fields": json.dumps([data_type.data_key]),
            "control_limits[enabled]": True,
            "control_limits[sigma]": 3,
            "center_line": "mean",
        }
    )
    response = client.get(url, headers={"Content-Type": "application/json"})

    # Check the request was successful
    assert response.status_code == 200, response.json

    # unknown=EXCLUDE ensures we don't keep the ID field when we load at this point
    data = TrendSchema(many=True, unknown=EXCLUDE).load(response.json)

    # Check that there are 4 series (mean, stdev, raw data, outliers)
    assert len(data) == 4

    # Test that this is valid plot data
    plot({"data": data}, validate=True, auto_open=False) 
Example #23
Source File: by_plotly.py    From OnePy with MIT License 5 votes vote down vote up
def plot2(self, ticker=None, notebook=False):

        returns_df = self.balance_df.pct_change(
        ).dropna()

        returns_df.columns = ['returns']
        fig = plotly.tools.make_subplots(
            rows=5, cols=2,
            shared_xaxes=True,
            vertical_spacing=0.001)

        fig['layout'].update(height=1500)

        self.append_trace(fig, self.positions_df, 2, 1)
        self.append_trace(fig, self.balance_df, 3, 1)
        self.append_trace(fig, self.holding_pnl_df, 4, 1)
        self.append_trace(fig, self.commission_df, 5, 1)
        self.append_trace(fig, self.margin_df, 1, 1)
        self.append_trace(fig, returns_df, 2, 2, 'bar')
        # fig['layout']['showlegend'] = True

        if notebook:
            plotly.offline.init_notebook_mode()
            py.iplot(fig, filename='OnePy_plot.html', validate=False)
        else:
            py.plot(fig, filename='OnePy_plot.html', validate=False) 
Example #24
Source File: plot.py    From sound_field_analysis-py with MIT License 5 votes vote down vote up
def plot3D(vizMTX, style='shape', layout=None, normalize=True, logScale=False):
    """Visualize matrix data, such as from makeMTX(Pnm, dn)

    Parameters
    ----------
    vizMTX : array_like
        Matrix holding spherical data for visualization
    layout : plotly.graph_objs.Layout, optional
        Layout of plot to be displayed offline
    style : string{'shape', 'sphere', 'flat'}, optional
        Style of visualization. [Default: 'shape']
    normalize : bool, optional
        Toggle normalization of data to [-1 ... 1] [Default: True]
    logScale : bool, optional
        Toggle conversion logScale [Default: False]

    # TODO
    # ----
    # Colorization, contour plot
    """

    if style == 'flat':
        layout = go.Layout(
            scene=dict(
                xaxis=dict(range=[0, 360]),
                yaxis=dict(range=[0, 181]),
                aspectmode='manual',
                aspectratio=dict(x=3.6, y=1.81, z=1)
            )
        )

    showTrace(genVisual(vizMTX, style=style, normalize=normalize, logScale=logScale), layout=layout) 
Example #25
Source File: utils.py    From wonambi with GNU General Public License v3.0 5 votes vote down vote up
def save_plotly_fig(fig, name):
    div = plot(fig, include_plotlyjs=False, output_type='div', show_link=False)
    with (PLOTLY_PATH / (name + '.html')).open('w') as f:
        f.write(div) 
Example #26
Source File: plotting.py    From pycls with MIT License 5 votes vote down vote up
def prepare_plot_data(log_files, names, metric="top1_err"):
    """Load logs and extract data for plotting error curves."""
    plot_data = []
    for file, name in zip(log_files, names):
        d, data = {}, logging.sort_log_data(logging.load_log_data(file))
        for phase in ["train", "test"]:
            x = data[phase + "_epoch"]["epoch_ind"]
            y = data[phase + "_epoch"][metric]
            d["x_" + phase], d["y_" + phase] = x, y
            d[phase + "_label"] = "[{:5.2f}] ".format(min(y) if y else 0) + name
        plot_data.append(d)
    assert len(plot_data) > 0, "No data to plot"
    return plot_data 
Example #27
Source File: generate_qc_plots.py    From panaroo with MIT License 5 votes vote down vote up
def generate_qc_plot(method, input_files, outdir, n_cpu, ref_db=None):

    # plot MDS
    if method in ["mds", "all"]:
        dist_mat, file_names = get_mash_dist(input_gffs=input_files,
                                             outdir=outdir,
                                             n_cpu=n_cpu,
                                             quiet=True)
        plot_MDS(dist_mat, file_names, outdir)

    # plot number of genes
    if method in ["ngenes", "all"]:
        plot_ngenes(input_gffs=input_files, outdir=outdir)

    # plot number of contigs
    if method in ["ncontigs", "all"]:
        plot_ncontigs(input_gffs=input_files, outdir=outdir)

    # plot contamination scatter plot
    if (method in ["contam", "all"]):
        if ref_db is None:
            print(
                "No reference mash database given! Skipping contamination plot..."
            )
            print(("One can be downloaded from https://mash.readthedocs.io" +
                   "/en/latest/tutorials.html#screening-a-read-set-for" +
                   "-containment-of-refseq-genomes"))
        else:
            mash_contam_file = get_mash_contam(input_gffs=input_files,
                                               mash_ref=ref_db,
                                               n_cpu=n_cpu,
                                               outdir=outdir)
            plot_mash_contam(mash_contam_file=mash_contam_file, outdir=outdir)

    return 
Example #28
Source File: image.py    From PyBloqs with GNU Lesser General Public License v2.1 5 votes vote down vote up
def plot_format(plot_format=None, dpi=None):
    """
    Temporarily set the plot formatting settings

    :param plot_format: The plot format (e.g 'png')
    :type plot_format:  str
    :param dpi:         The DPI of the plots
    :type dpi:          int
    """
    old = get_plot_format()
    set_plot_format(plot_format, dpi)
    yield
    set_plot_format(*old) 
Example #29
Source File: HydroSEDPlots.py    From WMF with GNU General Public License v3.0 5 votes vote down vote up
def Plot_Storages(self, StoragePath, PathFigure):
        '''Hace un plot del storage en el periodo de simulacion'''
        #Lee los datos 
        Data = pd.read_csv(StoragePath, skiprows=4, index_col=6, parse_dates=True)
        #Hace la figura
        fig = tools.make_subplots(rows=5, cols=1)
        for c,key in enumerate(Data.columns.values[1:].tolist()):
            trace1 = go.Scatter(
                x = Data.index.to_pydatetime(),
                y = Data[key].values,
                name = key,
                line = {'width':3},
                fill='tozeroy',
            )
            fig.append_trace(trace1, c+1, 1)
        fig['layout'].update(height=600, width=600,
            showlegend = False,
            yaxis=dict(title='Estado [mm]',),
            margin=dict(
                l=50,
                r=50,
                b=50,
                t=50,
                pad=4
            ))
        plot(fig,filename=PathFigure, auto_open = False) 
Example #30
Source File: HydroSEDPlots.py    From WMF with GNU General Public License v3.0 5 votes vote down vote up
def Plot_CDC_caudal(self,pathFigure,dfQobs,dfQsim):
        Qs=np.sort(np.array(dfQsim.values))
        Qo=np.sort(np.array(dfQobs.values))
        porcen_s=[]
        porcen_o=[]
        
        for i in range(len(Qo)):
            porcen_o.append((len(Qo[Qo>Qo[i]]))/float(len(Qo))*100)
        for i in range(len(Qs)):
            porcen_s.append((len(Qs[Qs>Qs[i]]))/float(len(Qs))*100)
            
        trace_high = go.Scatter(
                x=porcen_s,
                y=Qs,
                name = "Q simulado",
                line = dict(color = 'red'),
                opacity = 0.8)

        trace_low = go.Scatter(
                        x=porcen_o,
                        y=Qo,
                        name = "Q observado",
                        line = dict(color = 'blue'),
                        opacity = 0.8)

        data = [trace_high,trace_low]

        layout = dict(showlegend = False,
            width=500,
            height=400,
            xaxis = dict(
                title='Porcentaje de Excedencia'),
            yaxis=dict(
                title='$Caudal [m^3/s]$')
    
        )
        fig = dict(data=data, layout=layout)
        #Guarda el html
        plot(fig,filename=pathFigure, auto_open = False)