Ejemplo n.º 1
0
def test_bad_format_file():
    fig = simple_figure()
    local_scope = PlotlyScope()
    with pytest.raises(ValueError) as e:
        local_scope.transform(fig, format='bogus')

    e.match("Invalid format")
Ejemplo n.º 2
0
def test_missing_mapbox_token():
    fig = mapbox_figure()
    local_scope = PlotlyScope(mapbox_access_token=None)
    with pytest.raises(ValueError) as e:
        local_scope.transform(fig)

    e.match("access token")
Ejemplo n.º 3
0
class Kaleido:
    def __init__(self):
        # Init scopes
        if not STATIC_EXPORT:
            raise ImportError(
                "Static export is not possible due to missing dependencies")
        self.plotly_scope = PlotlyScope()

    def render_plotly_svg(self, fig, width=None, height=None):
        """
        Function to render a plotly figure in SVG inside jupyter
        """
        if STATIC_EXPORT:
            svg_fig = self.plotly_scope.transform(fig,
                                                  format="svg",
                                                  width=width,
                                                  height=height)
            return SVG(svg_fig)

    def export_plotly_svg(self, fig, fn, width=None, height=None):
        """
        Function to export a plotly figure to SVG
        """
        if STATIC_EXPORT:
            svg_fig = self.plotly_scope.transform(fig,
                                                  format="svg",
                                                  width=width,
                                                  height=height)
            with open(fn, mode="wb") as fp:
                fp.write(svg_fig)
Ejemplo n.º 4
0
def get_table_from_sheet(date):
    month = date.strftime("%B")
    result = SheetService().read_sheet_multiple(
        SPREADSHEET_ID, [f'{month}!A2:C', f'{month}!E2:G', f'{month}!I2:K'],
        major_dimension='COLUMNS')
    values = result.get('valueRanges', [])
    header = []
    l_ = []
    if len(values) > 0:
        for val in values:
            header = header + [item[0] for item in val['values']]
            l_ = l_ + [i[1:] for i in val['values']]
        scope = PlotlyScope()
        fig = go.Figure(data=[
            go.Table(columnwidth=[80, 150, 100, 80, 150, 100, 100, 100],
                     header=dict(values=header),
                     cells=dict(values=l_,
                                fill=dict(color=[
                                    'lightgreen', 'lightgreen', 'lightgreen',
                                    '#ff9982', '#ff9982', '#ff9982', '#ffbf70',
                                    '#ffbf70'
                                ]),
                                height=30))
        ])
        test = scope.transform(fig, format="png", scale=2)
        str_file = io.BytesIO(test)
        return str_file
    else:
        return None
Ejemplo n.º 5
0
 def save_static(self, figformat):
     scope = PlotlyScope()
     with open(self.path.replace('html', figformat), "wb") as f:
         f.write(scope.transform(self.fig, format=figformat))
         logging.info(
             f"Saved {self.path.replace('.html', '')}  as {figformat} (or png for --legacy)"
         )
Ejemplo n.º 6
0
def generate(data, title: str, format: str = "svg") -> go.Figure:
    datetimes = []
    prices = []
    for kp in data:
        if kp['price'] is not None and kp['date'] is not None:
            if type(kp['date']) != 'datetime':
                dt = datetime.datetime.strptime(kp['date'], "%Y-%m-%d")
                datetimes.append(dt)
            else:
                datetimes.append(kp['date'])
            prices.append(kp['price'])
        
    fig = go.Figure(
        data = go.Scatter(x=datetimes, y=prices), 
        layout = dict( 
            title = dict(
                text=title
            )
        )
    )

    scope = PlotlyScope()
    img = scope.transform(fig, format=format)
    # img = plotly.io.to_image(fig=fig, format=format)
    return img
Ejemplo n.º 7
0
def _create_donut(df, lang, filename, width, height, fontsize):
    scope = PlotlyScope()
    sentiment = get_sentiment(df, lang)
    labels, values = dict_to_list(sentiment)
    if lang == "tr":
        labels = ["Pozitif", "Nötr", "Negatif"]
    if lang == "en":
        labels = [label.capitalize() for label in labels]
    colors = ["darkgreen", "lightgreen", "red"]
    fig = go.Figure(data=[
        go.Pie(labels=labels,
               values=values,
               hole=0.5,
               textinfo="label+percent+value",
               textposition="inside")
    ])
    fig.update_traces(marker=dict(colors=colors),
                      textfont_size=fontsize,
                      showlegend=False)
    fig.update_layout(margin=dict(l=0, r=0, b=0, t=0, pad=4),
                      paper_bgcolor="rgba(0,0,0,0)",
                      plot_bgcolor="rgba(0,0,0,0)",
                      width=width,
                      height=height)
    fname_stamped = filename + "".join(str(time()).split("."))
    donuts_filenames[filename] = "img/" + fname_stamped + ".svg"
    with open(f"mint/static/img/{fname_stamped}.svg", "wb") as f:
        f.write(scope.transform(fig, format="svg"))
Ejemplo n.º 8
0
    def datauri_from_fig(fig,
                         fmt: str = "png",
                         width: int = 600,
                         height: int = 400,
                         scale: int = 4) -> str:
        """
        Generate a data URI from a Plotly Figure.

        :param fig: Plotly Figure object or corresponding dictionary
        :param fmt: "png", "jpg", etc. (see PlotlyScope for supported formats)
        :param width: width in pixels
        :param height: height in pixels
        :param scale: scale factor
        :return:
        """

        from kaleido.scopes.plotly import PlotlyScope

        scope = PlotlyScope()
        output = scope.transform(fig,
                                 format=fmt,
                                 width=width,
                                 height=height,
                                 scale=scale)
        image = b64encode(output).decode("ascii")

        return f"data:image/{fmt};base64,{image}"
Ejemplo n.º 9
0
def test_plotlyjs_file_url():
    fig = simple_figure()
    plotlyjs_url = local_plotlyjs_url
    local_scope = PlotlyScope(plotlyjs=plotlyjs_url)

    result = local_scope.transform(fig, format='png', width=700, height=500, scale=1)
    expected = load_baseline('simple', 'png')
    assert result == expected
Ejemplo n.º 10
0
def save_fig(date_str, new=True):
    '''Saves either new/total plot for a given date YYYY-MM-DD
    as a .png file.'''
    if new:
        kind = 'new'
    else:
        kind = 'total'

    fig = create_fig(date_str, new)
    scope = PlotlyScope()
    with open(f'{kind}_cases/{date_str}_{kind}_cases.png', 'wb') as f:
        f.write(scope.transform(fig, format='png'))
Ejemplo n.º 11
0
def boxplot(dataset, title, render="colab", filename='figure.png'):
    fig = go.Figure()
    fig.add_trace(
        go.Box(x=dataset,
               name=str(title),
               fillcolor=L_BLUE_BOX,
               marker_color=L_YELOW,
               marker_size=10,
               line_width=1.5,
               boxmean=True))
    fig.update_layout(height=250,
                      paper_bgcolor=COLAB_BKGROUND,
                      font={'color': ORANGE},
                      margin={
                          'l': 50,
                          't': 5,
                          'b': 30
                      },
                      plot_bgcolor=PLOT_BKGROUND,
                      xaxis={
                          'gridcolor': BLACK_GRID,
                          'zerolinecolor': BLACK_GRID
                      },
                      yaxis={
                          'autorange': True,
                          'showgrid': True,
                          'zeroline': True,
                          'dtick': 5,
                          'gridcolor': BLACK_GRID,
                          'gridwidth': 1,
                          'zerolinecolor': BLACK_GRID,
                          'zerolinewidth': 4
                      },
                      showlegend=False,
                      hovermode='x',
                      hoverlabel=dict(bgcolor=PLOT_BKGROUND,
                                      font_size=14,
                                      font_family="verdana"))
    if render == 'png':
        scope = PlotlyScope()
        with open(filename, "wb") as f:
            f.write(scope.transform(fig, format="png"))
        display(Image(filename=filename))
    else:
        fig.show()
Ejemplo n.º 12
0
def plot_meter(value,
               reference=10,
               render="colab",
               filename='figure.png',
               title='Error medio'):
    '''Medidor tipo `barra horizontal` de una sola magnitud'''
    fig = go.Figure(
        go.Indicator(mode="number+gauge+delta",
                     gauge={
                         'shape': "bullet",
                         'bgcolor': PLOT_BKGROUND,
                         'bar': {
                             'color': L_GREEN
                         }
                     },
                     align='center',
                     value=value,
                     delta={'reference': reference},
                     domain={
                         'x': [0, 1],
                         'y': [0, 1]
                     },
                     title={
                         'text': "<b style = 'color: " + ORANGE + ";'>" +
                         title + "</b>",
                         'font': {
                             "size": 18
                         }
                     }))
    fig.update_layout(height=50,
                      paper_bgcolor=COLAB_BKGROUND,
                      font={'color': ORANGE},
                      margin={
                          'l': 150,
                          't': 0,
                          'b': 0
                      })
    if render == 'png':
        scope = PlotlyScope()
        with open(filename, "wb") as f:
            f.write(scope.transform(fig, format="png"))
        display(Image(filename=filename))
    else:
        fig.show()
Ejemplo n.º 13
0
def plot_pattcorr(PC, labels, plotpath, lats, latn):
    """
    Plot pattern correlation curves as a function of lead time.
    :param PC:
    :type PC:
    :param labels:
    :type labels:
    :param plotpath:
    :type plotpath:
    :param region:
    :type region: str
    :return:
    :rtype:
    """

    latstring = get_latstring(lats, latn)

    plttype = "png"
    plotname = plotpath + "PatternCorrelationHovmoeller." + plttype
    nlines = len(labels)

    colors = ['black', 'dodgerblue', 'orange', 'seagreen', 'firebrick']

    scope = PlotlyScope()
    fig = go.Figure()
    for ll in np.arange(0, nlines):
        fig.add_trace(
            go.Scatter(x=PC['fchrs'],
                       y=PC[:, ll],
                       mode='lines',
                       name=labels[ll],
                       line=dict(color=colors[ll], width=2)))

    fig.update_layout(title=latstring)

    fig.update_xaxes(ticks="", tick0=0, dtick=24, title_text='lead time (h)')
    fig.update_yaxes(ticks="",
                     range=[0, 1],
                     dtick=0.1,
                     title_text='correlation')

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))
Ejemplo n.º 14
0
def plot_activity(act, wavename, labels, plotpath, fchr=[]):
    """
    Plot pattern correlation curves as a function of lead time.
    :param act:
    :type act:
    :param labels:
    :type labels:
    :return:
    :rtype:
    """

    plttype = "png"
    plotname = plotpath + wavename + "Activity." + plttype
    if fchr:
        plotname = plotpath + wavename + "Activity_f" + f"{fchr:03d}" + "." + plttype

    nlines, ntim = act.shape

    timestr = get_timestr(act['time'])

    colors = ['black', 'dodgerblue', 'orange', 'seagreen', 'firebrick']

    scope = PlotlyScope()
    fig = go.Figure()
    for ll in np.arange(nlines):
        fig.add_trace(
            go.Scatter(x=timestr,
                       y=act[ll, :].values,
                       mode='lines',
                       name=labels[ll],
                       line=dict(color=colors[ll], width=2)))

    fig.update_layout(title=wavename + " FH" + f"{fchr:03d}",
                      yaxis=dict(range=[0, 25]))

    #fig.update_xaxes(ticks="", tick0=0, dtick=12, title_text='date')
    fig.update_yaxes(ticks="", tick0=0, dtick=1., title_text='activity')

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))
Ejemplo n.º 15
0
def _create_timeviz_donut(df, lang, filename, width, height, fontsize, metric):
    # Template function for creating donut graphs based on time segments
    # For more info about time segments, check time_utils.py
    scope = PlotlyScope()
    labels, values = None, None
    if metric not in ["weekdays", "hours"]:
        raise ValueError("weekdays and hours are available time viz metrics")
    if metric == "weekdays" and lang not in ["tr", "en"]:
        raise ValueError("parameter lang should be either en or tr")
    if metric == "weekdays":
        scores = get_weekdays_score(df)
        labels, values = dict_to_list(scores)
        if lang == "tr":
            labels = ["Hafta içi", "Hafta sonu"]
        if lang == "en":
            labels = [label.capitalize() for label in labels]
    if metric == "hours":
        scores = get_hours_score(df)
        labels, values = dict_to_list(scores)
        labels = [
            "00:00 - 06:59", "07:00 - 12:59", "13:00 - 17:59", "18:00 - 23:59"
        ]
    fig = go.Figure(data=[
        go.Pie(labels=labels,
               values=values,
               hole=0.5,
               textinfo="label+percent+value",
               textposition="inside")
    ])
    fig.update_traces(textfont_size=fontsize, showlegend=False)
    fig.update_layout(margin=dict(l=0, r=0, b=0, t=0, pad=4),
                      paper_bgcolor="rgba(0,0,0,0)",
                      plot_bgcolor="rgba(0,0,0,0)",
                      width=width,
                      height=height)
    fname_stamped = filename + "".join(str(time()).split("."))
    timeviz_filenames[filename] = "img/" + fname_stamped + ".svg"
    with open(f"mint/static/img/{fname_stamped}.svg", "wb") as f:
        f.write(scope.transform(fig, format="svg"))
Ejemplo n.º 16
0
def plot_skill(skill, wavename, labels, plotpath):
    """
    Plot pattern correlation curves as a function of lead time.
    :param skill:
    :type skill:
    :param labels:
    :type labels:
    :return:
    :rtype:
    """

    plttype = "png"
    plotname = plotpath + wavename + "Skill." + plttype

    nfchr, nlines = skill.shape

    colors = ['dodgerblue', 'orange', 'seagreen', 'firebrick']

    scope = PlotlyScope()
    fig = go.Figure()
    for ll in np.arange(nlines):
        fig.add_trace(
            go.Scatter(x=skill['fchrs'],
                       y=skill[:, ll],
                       mode='lines',
                       name=labels[ll],
                       line=dict(color=colors[ll], width=2)))

    fig.update_layout(title=wavename + " skill", yaxis=dict(range=[0, 1]))

    fig.update_xaxes(ticks="", tick0=0, dtick=24, title_text='lead time (h)')
    fig.update_yaxes(ticks="",
                     tick0=0,
                     dtick=0.1,
                     title_text='skill correlation')

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))
Ejemplo n.º 17
0
def test_figure_size():
    # Create mocked scope
    scope = PlotlyScope()
    transform_mock = Mock(return_value={"code": 0, "result": "image"})
    scope._perform_transform = transform_mock

    # Set defualt width / height
    scope.default_width = 543
    scope.default_height = 567
    scope.default_format = "svg"
    scope.default_scale = 2

    # Make sure default width/height is used when no figure
    # width/height specified
    transform_mock.reset_mock()
    fig = go.Figure()
    scope.transform(fig)
    transform_mock.assert_called_once_with(fig.to_dict(),
                                           format="svg",
                                           scale=2,
                                           width=543,
                                           height=567)

    # Make sure figure's width/height takes precedence over defaults
    transform_mock.reset_mock()
    fig = go.Figure().update_layout(width=123, height=234)
    scope.transform(fig)
    transform_mock.assert_called_once_with(fig.to_dict(),
                                           format="svg",
                                           scale=2,
                                           width=123,
                                           height=234)

    # Make sure kwargs take precedence over Figure layout values
    transform_mock.reset_mock()
    fig = go.Figure().update_layout(width=123, height=234)
    scope.transform(fig, width=987, height=876)
    transform_mock.assert_called_once_with(fig.to_dict(),
                                           format="svg",
                                           scale=2,
                                           width=987,
                                           height=876)
Ejemplo n.º 18
0
def main():
    # Calcular parâmetros iniciais fixos da tubeira
    v_test_rad, v_test_deg = v(M_TEST)

    A_test_ratio = A_ratio(M_TEST)

    theta_1_rad, theta_1_deg = empirical_theta_1(v_test_rad, A_test_ratio)

    v_1_rad = v_test_rad - theta_1_rad
    v_1_deg = v_test_deg - theta_1_deg

    M_1 = M_from_v(v_1_rad)

    # Determinar coordenadas depois do ponto de inflexão, utilizando o método de Foelsch
    x_final_curve, y_final_curve = foelsch(Y_0, theta_1_rad, v_1_rad,
                                           v_test_rad, M_1)

    y_1 = y_final_curve[0]

    # Determinar coordenadas antes do ponto de inflexão
    x_initial_curve, y_initial_curve = initial_curve(Y_0, y_1, theta_1_rad)

    np.savetxt("nozzle_x.csv",
               np.concatenate([x_initial_curve, x_final_curve]),
               fmt='%s',
               delimiter=";")
    np.savetxt("nozzle_y.csv",
               np.concatenate([y_initial_curve, y_final_curve]),
               fmt='%s',
               delimiter=";")

    # Plotar resultados
    fig, ax = plt.subplots()
    ax.plot(x_initial_curve, y_initial_curve, 'r-')
    ax.plot(x_initial_curve, -y_initial_curve, 'r-')
    ax.plot(x_final_curve, y_final_curve, 'r-')
    ax.plot(x_final_curve, -y_final_curve, 'r-')
    ax.plot(x_initial_curve, np.zeros(x_initial_curve.shape), 'k--')
    ax.plot(x_final_curve, np.zeros(x_final_curve.shape), 'k--')
    ax.set_title("")
    ax.set_xlabel("")
    ax.set_ylabel("")

    plt.xlim(x_initial_curve[0], x_final_curve[-1] * 1.05)
    plt.ylim(-y_final_curve[-1] * 2, y_final_curve[-1] * 2)
    plt.show()

    throat_index = np.where(y_initial_curve == 10)[0][0]

    # Quasi Unidimensional
    graph_y_points = list(
        float_range(0, 200,
                    max(y_final_curve) / len(y_final_curve)))
    mach_matriz = []
    for i in range(len(graph_y_points)):
        mach_matriz.append(
            add_line_on_quasi_graph(
                graph_y_points[i],
                np.concatenate([y_initial_curve[throat_index:],
                                y_final_curve]),
                len(
                    np.concatenate(
                        [x_initial_curve[throat_index:], x_final_curve]))))

    # Espelhar resultados de Mach e pontos de y
    mirror = mach_matriz[::-1]
    mirror_y = [-x for x in graph_y_points[::-1]]

    scope = PlotlyScope()
    fig_quasi_unidimensional = make_subplots(rows=1, cols=1)
    fig_quasi_unidimensional.add_trace(
        go.Heatmap(z=mirror + mach_matriz,
                   x=np.concatenate(
                       [x_initial_curve[throat_index:], x_final_curve]),
                   y=mirror_y + graph_y_points,
                   colorbar=dict(title='Mach', titleside='right'),
                   connectgaps=True,
                   zsmooth='best'), 1, 1)
    fig_quasi_unidimensional.update
    fig_quasi_unidimensional.update_yaxes(title_text="Y axis (mm)",
                                          row=1,
                                          col=1)
    fig_quasi_unidimensional.update_xaxes(title_text="X axis (mm)",
                                          row=1,
                                          col=1)
    with open("quasi_unidimensional_graph.png", "wb") as f:
        f.write(scope.transform(fig_quasi_unidimensional, format="png"))
Ejemplo n.º 19
0
def hovmoeller(data,
               lon,
               time,
               datestrt,
               datelast,
               plotpath,
               lats,
               latn,
               spd,
               source,
               pltvarname,
               lev=[],
               cmin=[],
               cmax=[],
               cspc=[]):
    """
    Main driver for plotting Hovmoeller diagrams.
    :param data: input data, should be (time, lon)
    :type data: numeric
    :param lon: longitude coordinate of data
    :type lon: float
    :param time: time coordinate of data
    :type time: datetime
    :param datestrt: start date for Hovmoeller, used in plot file name
    :type datestrt: str
    :param datelast: end date for Hovmoeller, used in plot file name
    :type datelast: str
    :param plotpath: path for saving the figure
    :type plotpath: str
    :param lats: southern latitude limit of the average
    :type lats: float
    :param latn: northern latitude limit of the average
    :type latn: float
    :param spd: number of observations per day
    :type spd: int
    :param source: source of the data, e.g. (ERAI, TRMM, ...), used in plot file name
    :type source: str
    :param pltvarname: name of variable to be plotted
    :type pltvarname: str
    :param lev: vertical level of data (optional)
    :type lev: str
    :param cmin: contour level minimum (optional)
    :type cmin: float
    :param cmax: contour level maximum (optional)
    :type cmax: float
    :param cspc: contour spacing (optional)
    :type cspc: float
    :return: none
    :rtype: none
    """
    """
    Set plot type and plot file name.
    """
    plttype = "png"
    plotname = plotpath + "Hovmoeller_" + source + pltvarname + lev + "_" + str(
        datestrt) + "-" + str(datelast) + "." + plttype
    """
    Set plot resources: colormap, time string, contour levels, latitude band string
    """
    cmap_rgb = hov_resources(pltvarname)

    timestr = get_timestr(time)

    if (not cmin) or (not cmax) or (not cspc):
        cmin, cmax, cspc = get_clevels(pltvarname)

    latstring = get_latstring(lats, latn)
    """
    Generate the Hovmoeller plot.
    """
    scope = PlotlyScope()
    fig = go.Figure()

    fig.add_trace(
        go.Contour(z=data.values,
                   x=lon,
                   y=timestr,
                   colorscale=cmap_rgb,
                   contours=dict(start=cmin,
                                 end=cmax,
                                 size=cspc,
                                 showlines=False),
                   colorbar=dict(title=data.attrs['units'],
                                 len=0.6,
                                 lenmode='fraction')))

    fig.update_layout(title=source + " " + pltvarname + lev,
                      width=600,
                      height=900,
                      annotations=[
                          go.layout.Annotation(x=300,
                                               y=timestr[5],
                                               xref="x",
                                               yref="y",
                                               text=latstring,
                                               showarrow=False,
                                               bgcolor="white",
                                               opacity=0.9,
                                               font=dict(size=16))
                      ])

    fig.update_xaxes(ticks="inside", tick0=0, dtick=30, title_text='longitude')
    fig.update_yaxes(autorange="reversed", ticks="inside", nticks=11)

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))

    return
Ejemplo n.º 20
0
from kaleido.scopes.plotly import PlotlyScope
import plotly.graph_objects as go
scope = PlotlyScope()

fig = go.Figure(data=[go.Scatter(y=[1, 3, 2])])
with open("figure.png", "wb") as f:
    f.write(scope.transform(fig, format="png"))
Ejemplo n.º 21
0
def plot_vertcoh(coh,
                 px,
                 py,
                 levels,
                 labels,
                 titlestr,
                 plotname,
                 plotpath,
                 lats,
                 latn,
                 xlim=[0, 0.5]):
    """
    Plot averaged coherence and phase values by level.
    :param coh: Averaged coherence values. nvar x nlevels
    :param px: Averaged phase angle (x-component) values. nvar x nlevels
    :param py: Averaged phase angle (y-component) values. nvar x nlevels
    :param levels: Vertical level coordinate.
    :param labels: Labels for each variable, should include variable and symm/ anti-symm tag.
    :param titlestr: Title for the plot, should include CCEW/ MJO tag and variable name for var1 (usually precip).
    :param plotname: Name for the plot to be saved under.
    :param plotpath: Path for the plot to be saved at.
    :param lats: Southern latitude value the spectra were averaged over.
    :param latn: Northern latitude value the spectra were averaged over.
    :param xlim: optional parameter specifying the maximum coherence value on the x-axis
    :return:
    """

    # compute phase angle (in degrees) from x-y components.
    angcnst = 1.
    angle = np.arctan2(angcnst * px, py) * 180 / np.pi
    print(np.min(angle), np.max(angle))

    # latitude string for plot title
    latstring = get_latstring(lats, latn)

    # set up plotname for saving
    plttype = "png"
    plotname = plotpath + plotname + "." + plttype

    # plot
    nlines = len(labels)
    colors = ['firebrick', 'black', 'orange', 'dodgerblue', 'seagreen']
    symbols = ['circle', 'square', 'diamond', 'x', 'triangle-up']

    scope = PlotlyScope()
    fig = make_subplots(rows=1,
                        cols=2,
                        shared_yaxes=True,
                        horizontal_spacing=0.04)

    for ll in np.arange(0, nlines):
        fig.add_trace(go.Scatter(x=coh[ll, :],
                                 y=levels,
                                 mode='lines',
                                 name=labels[ll],
                                 line=dict(color=colors[ll], width=2)),
                      row=1,
                      col=1)
        fig.add_trace(go.Scatter(x=angle[ll, :],
                                 y=levels,
                                 mode='markers',
                                 showlegend=False,
                                 marker=dict(color=colors[ll],
                                             size=8,
                                             symbol=symbols[ll])),
                      row=1,
                      col=2)

    fig.add_annotation(x=-90,
                       y=50,
                       xref="x2",
                       yref="y2",
                       text="precip lags",
                       showarrow=False,
                       bgcolor="white",
                       opacity=0.8)
    fig.add_annotation(x=90,
                       y=50,
                       xref="x2",
                       yref="y2",
                       text="precip leads",
                       showarrow=False,
                       bgcolor="white",
                       opacity=0.8)

    fig.update_layout(title=titlestr + ' ' + latstring,
                      width=900,
                      height=600,
                      legend=dict(yanchor="bottom",
                                  y=0.01,
                                  xanchor="left",
                                  x=0.01))

    fig.update_xaxes(title_text='coh^2',
                     range=[xlim[0], xlim[1]],
                     row=1,
                     col=1)
    fig.update_xaxes(title_text='phase angle',
                     range=[-180, 180],
                     dtick=90,
                     row=1,
                     col=2)
    fig.update_yaxes(range=[100, 1000],
                     dtick=100,
                     title_text='hPa',
                     autorange="reversed",
                     row=1,
                     col=1)
    fig.update_yaxes(range=[100, 1000],
                     dtick=100,
                     autorange="reversed",
                     row=1,
                     col=2)

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))

    return
Ejemplo n.º 22
0
def plot_vertcoh_panel(ds_plot,
                       labels,
                       titlestr,
                       plotname,
                       plotpath,
                       lats,
                       latn,
                       xlim=[0, 0.5]):
    """
    Panel plot of averaged coherence and phase values by level.
    :param ds_plot: xarray dataset containing the data to plot. This includes nplot as an attribute and
    the source names and forecast hours. The
    :param labels: Labels for each variable, should include variable and symm/ anti-symm tag.
    :param titlestr: Title for the plot, should include CCEW/ MJO tag and variable name for var1 (usually precip).
    :param plotname: Name for the plot to be saved under.
    :param plotpath: Path for the plot to be saved at.
    :param lats: Southern latitude value the spectra were averaged over.
    :param latn: Northern latitude value the spectra were averaged over.
    :param xlim: optional parameter specifying the maximum coherence value on the x-axis
    :return:
    """

    # sources1 = ds_plot['sources1']
    # sources2 = ds_plot['sources2']
    nplot = int(ds_plot.attrs['nplot'])
    varnames = list(ds_plot.data_vars)
    sourcenames = ds_plot.attrs["sourcenames"]
    titles = []
    for name in sourcenames:
        titles.append(name)
        titles.append('')
    abcstrings = list(string.ascii_lowercase)

    # compute phase angle (in degrees) from x-y components.
    angcnst = 1.

    # latitude string for plot title
    latstring = get_latstring(lats, latn)

    # set up plotname for saving
    plttype = "png"
    plotname = plotpath + plotname + "." + plttype

    # plot
    nlines = len(labels)
    colors = ['firebrick', 'black', 'orange', 'dodgerblue', 'seagreen']
    symbols = ['circle', 'square', 'diamond', 'x', 'triangle-up']

    ncols = 4
    nrows = int(np.ceil(nplot / 2))
    scope = PlotlyScope()
    fig = make_subplots(rows=nrows,
                        cols=ncols,
                        shared_yaxes=True,
                        horizontal_spacing=0.04,
                        vertical_spacing=0.04,
                        subplot_titles=titles)

    for pp in np.arange(0, nrows):
        coh = ds_plot[varnames[pp * nplot]]
        try:
            levels = coh['plev']
        except KeyError:
            levels = coh['level']
        px = ds_plot[varnames[pp * nplot + 1]]
        py = ds_plot[varnames[pp * nplot + 2]]
        angle = np.arctan2(angcnst * px, py) * 180 / np.pi

        for ll in np.arange(0, nlines):
            if pp == 0:
                fig.add_trace(go.Scatter(x=coh[ll, :],
                                         y=levels,
                                         mode='lines',
                                         name=labels[ll],
                                         line=dict(color=colors[ll], width=2)),
                              row=pp + 1,
                              col=1)
            else:
                fig.add_trace(go.Scatter(x=coh[ll, :],
                                         y=levels,
                                         mode='lines',
                                         name=labels[ll],
                                         showlegend=False,
                                         line=dict(color=colors[ll], width=2)),
                              row=pp + 1,
                              col=1)
            fig.add_trace(go.Scatter(x=angle[ll, :],
                                     y=levels,
                                     mode='markers',
                                     showlegend=False,
                                     marker=dict(color=colors[ll],
                                                 size=8,
                                                 symbol=symbols[ll])),
                          row=pp + 1,
                          col=2)

        coh = ds_plot[varnames[pp * nplot + int(np.ceil(nplot / 2))]]
        try:
            levels = coh['plev']
        except KeyError:
            levels = coh['level']
        px = ds_plot[varnames[pp * nplot + int(np.ceil(nplot / 2)) + 1]]
        py = ds_plot[varnames[pp * nplot + int(np.ceil(nplot / 2)) + 2]]
        angle = np.arctan2(angcnst * px, py) * 180 / np.pi

        for ll in np.arange(0, nlines):
            fig.add_trace(go.Scatter(x=coh[ll, :],
                                     y=levels,
                                     mode='lines',
                                     showlegend=False,
                                     name=labels[ll],
                                     line=dict(color=colors[ll], width=2)),
                          row=pp + 1,
                          col=3)
            fig.add_trace(go.Scatter(x=angle[ll, :],
                                     y=levels,
                                     mode='markers',
                                     showlegend=False,
                                     marker=dict(color=colors[ll],
                                                 size=8,
                                                 symbol=symbols[ll])),
                          row=pp + 1,
                          col=4)

    for i in np.arange(2, nrows * ncols + 1, 2):
        istr = str(i)
        fig.add_annotation(x=-90,
                           y=50,
                           xref="x" + istr,
                           yref="y" + istr,
                           text="precip lags",
                           showarrow=False,
                           bgcolor="white",
                           opacity=0.8)
        fig.add_annotation(x=90,
                           y=50,
                           xref="x" + istr,
                           yref="y" + istr,
                           text="precip leads",
                           showarrow=False,
                           bgcolor="white",
                           opacity=0.8)

    for i in np.arange(1, nrows * ncols + 1):
        if i % 2 == 0:
            xpos = -180
        else:
            xpos = xlim[0]
        fig.add_annotation(x=xpos,
                           y=50,
                           xref="x" + str(i),
                           yref="y" + str(i),
                           text=abcstrings[i - 1],
                           showarrow=False,
                           bgcolor="white",
                           opacity=0.8)

    fig.update_layout(title=titlestr + ' ' + latstring,
                      width=1800,
                      height=1800,
                      legend=dict(yanchor="bottom",
                                  y=0.45,
                                  xanchor="left",
                                  x=0.15))

    for j in np.arange(1, ncols, 2):
        fig.update_xaxes(title_text='coh^2',
                         range=[xlim[0], xlim[1]],
                         row=nrows,
                         col=j)
        fig.update_xaxes(title_text='phase angle',
                         range=[-180, 180],
                         dtick=90,
                         row=nrows,
                         col=(j + 1))
        for i in range(nrows - 1):
            fig.update_xaxes(range=[xlim[0], xlim[1]], row=(i + 1), col=j)
            fig.update_xaxes(range=[-180, 180],
                             dtick=90,
                             row=(i + 1),
                             col=(j + 1))

    for i in range(nrows):
        fig.update_yaxes(range=[100, 1000],
                         dtick=100,
                         title_text='hPa',
                         autorange="reversed",
                         row=(i + 1),
                         col=1)
        for j in np.arange(2, ncols + 1):
            fig.update_yaxes(range=[100, 1000],
                             dtick=100,
                             autorange="reversed",
                             row=(i + 1),
                             col=j)

    with open(plotname, "wb") as f:
        f.write(scope.transform(fig, format=plttype))

    return
Ejemplo n.º 23
0
 def save_static(self):
     scope = PlotlyScope()
     with open(self.path.replace('html', 'png'), "wb") as f:
         f.write(scope.transform(self.fig, format="png"))
df["timestamp"] = df["timestamp"].transform(lambda x: x - 25000)
df = df[df["timestamp"] >= 0]

fig = px.line(df,
              x="timestamp",
              y="net.packets_sent.ib0",
              color="config",
              line_group="iteration",
              template=template,
              labels={
                  "timestamp": "time (ms)",
                  "net.packets_sent.ib0": "packets sent",
                  "config": "Dyconit configuration"
              })
with open(str(output_dir.joinpath("packets_over_time.pdf")), "wb") as f:
    f.write(scope.transform(fig, format="pdf"))

df = df.groupby(["iteration", "config"], as_index=False).max()
df["packets_per_second"] = df["net.packets_sent.ib0"] / (df["timestamp"] /
                                                         1000)
fig = px.box(df,
             x="config",
             y="packets_per_second",
             template=template,
             labels={
                 "config": "Dyconit policy",
                 "packets_per_second": "packets per second"
             })
with open(str(output_dir.joinpath("packets_per_second_over_policy.pdf")),
          "wb") as f:
    f.write(scope.transform(fig, format="pdf"))