Esempio n. 1
0
def printagraf(pontosx, pontosy, n, cor):

    plt.scatter(pontosx, pontosy, s=2, color=cor)
    #plt.plot(pontosx,pontosy,marker= 'o',label= 'Line 1')
    plt.xlabel('X ---------->')
    plt.ylabel('Y ---------->')
    if (n == 1):
        plt.title('Euler')
    elif (n == 2):
        plt.title('Euler Aprimorado')
    elif (n == 3):
        plt.title('Euler Inverso')
    elif (n == 4):
        plt.title('Runge Kutta')
    elif (n == 5):
        plt.title('Adams Bashford')
    elif (n == 6):
        plt.title('Adams Moulton')
    else:
        plt.title('Metodos Agrupados')
        plt.scatter(x, ey, s=2, color='black')
        plt.scatter(x, eay, s=2, color='red')
        plt.scatter(x, eiy, s=2, color='blue')
        plt.scatter(x, kf, s=2, color='orange')
        plt.scatter(x, aby, s=2, color='gray')
        plt.scatter(x, amy, s=2, color='green')

    plt.autoscale()
    plt.AutoLocator()
    plt.grid()
    plt.show()
Esempio n. 2
0
 def draw_plot(self, metrics, labels=None, ylabel=""):
     """
     metrics: One or more metrics parameters. Each represents the history
         of one metric.
     """
     metrics = metrics if isinstance(metrics, list) else [metrics]
     # Loop through metrics
     title = ""
     self.ax.yaxis.tick_right()
     self.ax.grid(which='both', axis='y')
     subax = self.ax.twinx()
     subax.set_yticks([])
     for i, m in enumerate(metrics):
         label = labels[i] if labels else m.name
         # TODO: make a sortig by label, to let always right order in the
         # parenthesis.
         # TODO: use a standard formating function for values
         #title += ("   " if title else "") + "{}: {}".format(label, m.data[-1])
         p = self.ax.plot(m.formatted_steps, m.data, label=label)
         # add the tag to the last point.
         if m.data[-1] is not None:
             subax.set_yticks(list(subax.get_yticks())+[m.data[-1]])
             subax.get_yticklabels()[-1].set_color(p[-1].get_color())
     subax.set_ylim(self.ax.get_ylim())
     self.ax.set_title(title)
     self.ax.set_ylabel(ylabel)
     self.ax.legend()
     self.ax.set_xlabel("Steps")
     self.ax.xaxis.set_major_locator(plt.AutoLocator())
Esempio n. 3
0
 def do_setting(ax, kind):
     setfn = getattr(ax, f"set_{kind}_locator")
     if maxn is not None:
         setfn(plt.MaxNLocator(maxn))
     elif multiple is not None:
         setfn(plt.MultipleLocator(multiple))
     else:
         setfn(plt.AutoLocator() if kind == "major" else AutoMinorLocator())
def plot_single(x, y, name, figsize=(20, 6)):
    fig, ax = plt.subplots(1, 1, figsize=figsize)

    g, = plt.plot(x, y, 'royalblue', label=name)

    ax.xaxis.set_major_locator(plt.AutoLocator())
    ax.legend([g], [g.get_label()])
    ax.set_ylabel(name.capitalize())

    fig.autofmt_xdate()
    plt.title(name.capitalize(), fontsize=16)
    plt.show()
Esempio n. 5
0
def minor_ticks(nx=5, ny=5, x=True, y=True):
    """
    Sets *n* minor tick marks per major tick for the x and y axes of the current figure.
       *nx: integer number of minor ticks for x, DEFAULT: 5
       *ny: integer number of minor ticks for y, DEFAULT: 5
       *x: True/False, DEFAULT: True
       *y: True/False, DEFAULT: True
    """

    ax = pyplot.gca()

    if x:
        ax.xaxis.set_major_locator(pyplot.AutoLocator())
        x_major = ax.xaxis.get_majorticklocs()
        dx_minor = (x_major[-1] - x_major[0]) / (len(x_major) - 1) / nx
        ax.xaxis.set_minor_locator(pyplot.MultipleLocator(dx_minor))
    if y:
        ax.yaxis.set_major_locator(pyplot.AutoLocator())
        y_major = ax.yaxis.get_majorticklocs()
        dy_minor = (y_major[-1] - y_major[0]) / (len(y_major) - 1) / ny
        ax.yaxis.set_minor_locator(pyplot.MultipleLocator(dy_minor))

    pyplot.plot()
    return
Esempio n. 6
0
 def draw_plot(self, metrics, labels=None, ylabel=""):
     """
     metrics: One or more metrics parameters. Each represents the history
         of one metric.
     """
     metrics = metrics if isinstance(metrics, list) else [metrics]
     # Loop through metrics
     title = ""
     for i, m in enumerate(metrics):
         label = labels[i] if labels else m.name
         # TODO: use a standard formating function for values
         title += ("   " if title else "") + "{}: {}".format(
             label, m.data[-1])
         self.ax.plot(m.formatted_steps, m.data, label=label)
     self.ax.set_title(title)
     self.ax.set_ylabel(ylabel)
     self.ax.legend()
     self.ax.set_xlabel("Steps")
     self.ax.xaxis.set_major_locator(plt.AutoLocator())
def plot_hist(returns, w, alpha=0.05, bins=50, height=6, width=10, ax=None):
    r"""
    Create a histogram of portfolio returns with the risk measures.

    Parameters
    ----------
    returns : DataFrame
        Assets returns.
    w : DataFrame of shape (n_assets, 1)
        Portfolio weights.
    alpha : float, optional
        Significante level of VaR, CVaR and EVaR. The default is 0.05.
    bins : float, optional
        Number of bins of the histogram. The default is 50.
    height : float, optional
        Height of the image in inches. The default is 6.
    width : float, optional
        Width of the image in inches. The default is 10.
    ax : matplotlib axis, optional
        If provided, plot on this axis. The default is None.

    Raises
    ------
    ValueError
        When the value cannot be calculated.

    Returns
    -------
    ax : matplotlib axis.
        Returns the Axes object with the plot for further tweaking.

    Example
    -------
    ::

        ax = plf.plot_hist(returns=Y, w=w1, alpha=0.05, bins=50, height=6,
                           width=10, ax=None)

    .. image:: images/Histogram.png


    """

    if not isinstance(returns, pd.DataFrame):
        raise ValueError("returns must be a DataFrame")

    if not isinstance(w, pd.DataFrame):
        raise ValueError("w must be a DataFrame")

    if w.shape[1] > 1 and w.shape[0] == 0:
        w = w.T
    elif w.shape[1] > 1 and w.shape[0] > 0:
        raise ValueError("w must be a  DataFrame")

    if returns.shape[1] != w.shape[0]:
        a1 = str(returns.shape)
        a2 = str(w.shape)
        raise ValueError("shapes " + a1 + " and " + a2 + " not aligned")

    if ax is None:
        ax = plt.gca()
        fig = plt.gcf()
        fig.set_figwidth(width)
        fig.set_figheight(height)

    a = np.array(returns, ndmin=2) @ np.array(w, ndmin=2)
    ax.set_title("Portfolio Returns Histogram")
    n, bins1, patches = ax.hist(a,
                                bins,
                                density=1,
                                edgecolor="skyblue",
                                color="skyblue",
                                alpha=0.5)
    mu = np.mean(a)
    sigma = np.std(a, axis=0, ddof=1).item()
    risk = [
        mu,
        mu - sigma,
        mu - rk.MAD(a),
        -rk.VaR_Hist(a, alpha),
        -rk.CVaR_Hist(a, alpha),
        -rk.EVaR_Hist(a, alpha)[0],
        -rk.WR(a),
    ]
    label = [
        "Mean: " + "{0:.2%}".format(risk[0]),
        "Mean - Std. Dev.(" + "{0:.2%}".format(-risk[1] + mu) + "): " +
        "{0:.2%}".format(risk[1]),
        "Mean - MAD(" + "{0:.2%}".format(-risk[2] + mu) + "): " +
        "{0:.2%}".format(risk[2]),
        "{0:.2%}".format(
            (1 - alpha)) + " Confidence VaR: " + "{0:.2%}".format(risk[3]),
        "{0:.2%}".format(
            (1 - alpha)) + " Confidence CVaR: " + "{0:.2%}".format(risk[4]),
        "{0:.2%}".format(
            (1 - alpha)) + " Confidence EVaR: " + "{0:.2%}".format(risk[5]),
        "Worst Realization: " + "{0:.2%}".format(risk[6]),
    ]
    color = [
        "b", "r", "fuchsia", "darkorange", "limegreen", "dodgerblue",
        "darkgrey"
    ]

    for i, j, k in zip(risk, label, color):
        ax.axvline(x=i, color=k, linestyle="-", label=j)

    # add a 'best fit' line
    y = (1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma *
                                                            (bins1 - mu))**2)
    ax.plot(
        bins1,
        y,
        "--",
        color="orange",
        label="Normal: $\mu=" + "{0:.2%}".format(mu) + "$%, $\sigma=" +
        "{0:.2%}".format(sigma) + "$%",
    )

    factor = (np.max(a) - np.min(a)) / bins

    ax.xaxis.set_major_locator(plt.AutoLocator())
    ax.set_xticklabels(["{:3.2%}".format(x) for x in ax.get_xticks()])
    ax.set_yticklabels(["{:3.2%}".format(x * factor) for x in ax.get_yticks()])
    ax.legend(loc="upper right")  # , fontsize = 'x-small')
    ax.grid(linestyle=":")
    ax.set_ylabel("Probability Density")

    fig = plt.gcf()
    fig.tight_layout()

    return ax
def plot_frontier(
    w_frontier,
    mu,
    cov=None,
    returns=None,
    rm="MV",
    rf=0,
    alpha=0.05,
    cmap="viridis",
    w=None,
    label="Portfolio",
    marker="*",
    s=16,
    c="r",
    height=6,
    width=10,
    t_factor=252,
    ax=None,
):
    r"""
    Creates a plot of the efficient frontier for a risk measure specified by
    the user.

    Parameters
    ----------
    w_frontier : DataFrame
        Portfolio weights of some points in the efficient frontier.
    mu : DataFrame of shape (1, n_assets)
        Vector of expected returns, where n_assets is the number of assets.
    cov : DataFrame of shape (n_features, n_features)
        Covariance matrix, where n_features is the number of features.
    returns : DataFrame of shape (n_samples, n_features)
        Features matrix, where n_samples is the number of samples and
        n_features is the number of features.
    rm : str, optional
        The risk measure used to estimate the frontier.
        The default is 'MV'. Posible values are:

        - 'MV': Standard Deviation.
        - 'MAD': Mean Absolute Deviation.
        - 'MSV': Semi Standard Deviation.
        - 'FLPM': First Lower Partial Moment (Omega Ratio).
        - 'SLPM': Second Lower Partial Moment (Sortino Ratio).
        - 'CVaR': Conditional Value at Risk.
        - 'EVaR': Conditional Value at Risk.
        - 'WR': Worst Realization (Minimax)
        - 'MDD': Maximum Drawdown of uncompounded returns (Calmar Ratio).
        - 'ADD': Average Drawdown of uncompounded returns.
        - 'DaR': Drawdown at Risk of uncompounded returns.
        - 'CDaR': Conditional Drawdown at Risk of uncompounded returns.
        - 'UCI': Ulcer Index of uncompounded returns.

    rf : float, optional
        Risk free rate or minimum aceptable return. The default is 0.
    alpha : float, optional
        Significante level of VaR, CVaR, EVaR, DaR and CDaR.
        The default is 0.05.
    cmap : cmap, optional
        Colorscale, represente the risk adjusted return ratio.
        The default is 'viridis'.
    w : DataFrame of shape (n_assets, 1), optional
        A portfolio specified by the user. The default is None.
    label : str, optional
        Name of portfolio that appear on plot legend.
        The default is 'Portfolio'.
    marker : str, optional
        Marker of w. The default is "*".
    s : float, optional
        Size of marker. The default is 16.
    c : str, optional
        Color of marker. The default is 'r'.
    height : float, optional
        Height of the image in inches. The default is 6.
    width : float, optional
        Width of the image in inches. The default is 10.
    t_factor : float, optional
        Factor used to annualize expected return and expected risks for
        risk measures based on returns (not drawdowns). The default is 252.
        
        .. math::
            
            \begin{align}
            \text{Annualized Return} & = \text{Return} \, \times \, \text{t_factor} \\
            \text{Annualized Risk} & = \text{Risk} \, \times \, \sqrt{\text{t_factor}}
            \end{align}
            
    ax : matplotlib axis, optional
        If provided, plot on this axis. The default is None.

    Raises
    ------
    ValueError
        When the value cannot be calculated.

    Returns
    -------
    ax : matplotlib Axes
        Returns the Axes object with the plot for further tweaking.

    Example
    -------
    ::

        label = 'Max Risk Adjusted Return Portfolio'
        mu = port.mu
        cov = port.cov
        returns = port.returns

        ax = plf.plot_frontier(w_frontier=ws, mu=mu, cov=cov, returns=returns,
                               rm=rm, rf=0, alpha=0.05, cmap='viridis', w=w1,
                               label=label, marker='*', s=16, c='r',
                               height=6, width=10, t_factor=252, ax=None)

    .. image:: images/MSV_Frontier.png


    """

    if not isinstance(w_frontier, pd.DataFrame):
        raise ValueError("w_frontier must be a DataFrame")

    if not isinstance(mu, pd.DataFrame):
        raise ValueError("mu must be a DataFrame")

    if not isinstance(cov, pd.DataFrame):
        raise ValueError("cov must be a DataFrame")

    if not isinstance(returns, pd.DataFrame):
        raise ValueError("returns must be a DataFrame")

    if returns.shape[1] != w_frontier.shape[0]:
        a1 = str(returns.shape)
        a2 = str(w_frontier.shape)
        raise ValueError("shapes " + a1 + " and " + a2 + " not aligned")

    if w is not None:
        if not isinstance(w, pd.DataFrame):
            raise ValueError("w must be a DataFrame")

        if w.shape[1] > 1 and w.shape[0] == 0:
            w = w.T
        elif w.shape[1] > 1 and w.shape[0] > 0:
            raise ValueError("w must be a column DataFrame")

        if returns.shape[1] != w.shape[0]:
            a1 = str(returns.shape)
            a2 = str(w.shape)
            raise ValueError("shapes " + a1 + " and " + a2 + " not aligned")

    if ax is None:
        ax = plt.gca()
        fig = plt.gcf()
        fig.set_figwidth(width)
        fig.set_figheight(height)

    mu_ = np.array(mu, ndmin=2)

    ax.set_ylabel("Expected Return")
    item = rmeasures.index(rm)
    x_label = rm_names[item] + " (" + rm + ")"
    ax.set_xlabel("Expected Risk - " + x_label)

    title = "Efficient Frontier Mean - " + x_label
    ax.set_title(title)

    X1 = []
    Y1 = []
    Z1 = []

    for i in range(w_frontier.shape[1]):
        weights = np.array(w_frontier.iloc[:, i], ndmin=2).T
        risk = rk.Sharpe_Risk(weights,
                              cov=cov,
                              returns=returns,
                              rm=rm,
                              rf=rf,
                              alpha=alpha)

        ret = mu_ @ weights
        ret = ret.item() * t_factor

        if rm not in ["MDD", "ADD", "CDaR", "UCI"]:
            risk = risk * t_factor**0.5

        ratio = (ret - rf) / risk

        X1.append(risk)
        Y1.append(ret)
        Z1.append(ratio)

    ax1 = ax.scatter(X1, Y1, c=Z1, cmap=cmap)

    if w is not None:
        X2 = []
        Y2 = []
        for i in range(w.shape[1]):
            weights = np.array(w.iloc[:, i], ndmin=2).T
            risk = rk.Sharpe_Risk(weights,
                                  cov=cov,
                                  returns=returns,
                                  rm=rm,
                                  rf=rf,
                                  alpha=alpha)
            ret = mu_ @ weights
            ret = ret.item() * t_factor

            if rm not in ["MDD", "ADD", "CDaR", "UCI"]:
                risk = risk * t_factor**0.5

            ratio = (ret - rf) / risk

            X2.append(risk)
            Y2.append(ret)

        ax.scatter(X2, Y2, marker=marker, s=s**2, c=c, label=label)
        ax.legend(loc="upper left")

    xmin = np.min(X1) - np.abs(np.max(X1) - np.min(X1)) * 0.1
    xmax = np.max(X1) + np.abs(np.max(X1) - np.min(X1)) * 0.1
    ymin = np.min(Y1) - np.abs(np.max(Y1) - np.min(Y1)) * 0.1
    ymax = np.max(Y1) + np.abs(np.max(Y1) - np.min(Y1)) * 0.1

    ax.set_ylim(ymin, ymax)
    ax.set_xlim(xmin, xmax)

    ax.xaxis.set_major_locator(plt.AutoLocator())

    ax.set_yticklabels(["{:.4%}".format(x) for x in ax.get_yticks()])
    ax.set_xticklabels(["{:.4%}".format(x) for x in ax.get_xticks()])

    ax.tick_params(axis="y", direction="in")
    ax.tick_params(axis="x", direction="in")

    ax.grid(linestyle=":")

    colorbar = ax.figure.colorbar(ax1)
    colorbar.set_label("Risk Adjusted Return Ratio")

    fig = plt.gcf()
    fig.tight_layout()

    return ax
Esempio n. 9
0
def plot_trace_file_3cols(nodes=None, trace=''):
    # nodes: only plot specified nodes' trace data (list)
    # trace: [CWND, RCWND, RTT]

    if not nodes:
        nodes = ['1', '2', '3', '4', '5', '6']
        output_filename = trace + '.png'
    else:
        output_filename = '-'.join(['-'.join(nodes), trace + '.png'])

    for i in nodes:
        trace_filename = '-'.join([filename_base, i, 'TCP', trace + '.txt'])
        plot_style = 's' if trace == 'RCWND' else '-'

        x_vals, y_vals = [], []

        with open(trace_filename, 'r') as f:
            for line in f:
                #time, old, new = re.match('([0-9\.]*)\W*([0-9\.]*)\W*([0-9\.]*)\W*')
                linedata = re.findall('([0-9\.]*)\W*', line)
                x_val, y_val = linedata[0], linedata[2]

                if trace == 'CWND' or trace == 'RCWND':  # cwnd size to packets
                    y_val = str(int(int(y_val) / int(packet_size)))

                if '.' in x_val:
                    x_vals.append(float(x_val))
                else:
                    x_vals.append(int(x_val))
                if '.' in y_val:
                    y_vals.append(float(y_val))
                else:
                    y_vals.append(int(y_val))

        plt.plot(x_vals,
                 y_vals,
                 colors[int(i) - 1] + plot_style,
                 linewidth=0.5,
                 antialiased=False,
                 label='Node ' + i)
        #plt.plot(x_vals, y_vals, colors[int(i)-1], linestyle='s', markersize=2, linewidth=0.3, antialiased=False, label='Node '+i)

        plt.xlabel('time (s)')
        if trace == 'CWND' or trace == 'RCWND':
            plt.ylabel('CWND size (packets)')
        if trace == 'RTT':
            plt.ylabel('RTT (s)')
        #plt.axis('tight')
        if len(nodes) == 1:
            plt.title('Node {} {}'.format(nodes[0], trace))
        elif len(nodes) == 6:
            plt.title('All nodes {}'.format(trace))
        elif len(nodes) > 1:
            plt.title('Nodes {} {}'.format(', '.join(nodes), trace))
        else:
            plt.title('Node 1-6 {}'.format(trace))

    ax = plt.axes()
    #ax.xaxis.set_major_locator(plt.MaxNLocator(5))
    #ax.yaxis.set_major_locator(plt.MaxNLocator(5))
    ax.xaxis.set_major_locator(plt.AutoLocator())
    ax.yaxis.set_major_locator(plt.AutoLocator())
    ax.legend()

    #plt.show()
    plt.savefig('./png/' + output_filename, bbox_inches='tight')
Esempio n. 10
0
 def plotValue(
     self,
     xlabel=[],
     ylabel=[],
     pdpi=100,
     fill=True,
     fontsize=10,
     xsize=2.5,
     ysize=2,
     xlimits=[],
     lang='EN',
     TextRender=True,
     AxisNameLong=True,
     frame=False,
     nYTicks=2,
     nXTicks=5,
     xAxisRot=False,
     trans=1.0,
     font='tex gyre pagella',
     Units=[],
     plotBuffer=0.1,
     color=DefaultColor,
     delta=0.5,
     padLabel=[],
 ):
     plt.rcParams['font.family'] = font
     rcParams.update({'figure.autolayout': True})
     rcParams.update(pgf_with_pdflatex)
     if not TextRender:
         rcParams.update({'svg.fonttype': 'none'})
     if self.Form == 'interval' or self.nalpha == 1:  # for interval plot
         xsize = 5
         ysize = 0.25
         fig = plt.figure(figsize=(xsize, ysize), dpi=pdpi)
         ax = fig.add_subplot(1, 1, 1)
         thick = 1**0.1 * 0.3
         yplaces = [0.5 + i for i in reversed(range(1))]
         ax.set_yticks(yplaces)
         if not xlabel:
             xlabel = r'Uncertain value'
         if not ylabel:
             ylabel = r'Parameter'
         ax.set_yticklabels([ylabel], horizontalalignment='left')
         ax.set_ylim((0, 1))
         start = self.Value[0, 0]
         end = self.Value[0, 1]
         pos = yplaces[0]
         ax.add_patch(
             patches.Rectangle((start, pos - delta / 2.0),
                               end - start,
                               thick,
                               color=color))
         pmin = np.min(self.Value)
         pmax = np.max(self.Value)
         ax.plot(
             (pmin * (1 - plotBuffer), pmax * (1 + plotBuffer)),
             (0, 0),
             'w',
             alpha=0.0,
         )
         sns.despine()
         nlmax = len(ylabel)
         yax = ax.get_yaxis()
         if not padLabel:
             padLabel = min(nlmax * 5.5, 175)
         yax.set_tick_params(direction='out', pad=padLabel)
         if not Units:
             ax.set_xlabel(xlabel)
         else:
             ax.set_xlabel(xlabel + ' [' + Units + ']')
         if xAxisRot:
             plt.setp(ax.get_xticklabels(), rotation='vertical')
         plt.xlim(
             (np.min(self.Value) -
              (np.max(self.Value) - np.min(self.Value)) / 5),
             (np.max(self.Value) +
              (np.max(self.Value) - np.min(self.Value)) / 5),
         )
     else:
         fig = plt.figure(figsize=(xsize, ysize), dpi=pdpi)
         ax = fig.add_subplot(1, 1, 1)
         mu = np.linspace(1, 0, np.size(self.Value, 0))
         xplot = np.concatenate(
             (np.flipud(self.Value[:, 0]), self.Value[:, 1]), axis=0)
         muplot = np.concatenate((np.flipud(mu), mu), axis=0)
         if fill:
             ax.fill_between(
                 self.Value[:, 0],
                 mu,
                 facecolor=color,
                 alpha=trans,
                 linewidth=0.0,
             )
             ax.fill_between(
                 [self.Value[0, 1], self.Value[0, 0]],
                 [1, 1],
                 facecolor=color,
                 alpha=trans,
                 linewidth=0.0,
             )
             ax.fill_between(
                 self.Value[:, 1],
                 mu,
                 facecolor=color,
                 alpha=trans,
                 linewidth=0.0,
             )
         ax.plot(xplot, muplot, 'k-', linewidth=1)
         plt.ylim(0, 1.10)
         if xlimits != []:
             plt.xlim(xlimits[0], xlimits[1])
         plt.xlabel(xlabel)
         plt.yticks(np.arange(0, 1 + (nYTicks - 1), 1 / (nYTicks - 1)))
         xloc = plt.MaxNLocator(nXTicks)
         # plt.MaxNLocator(nXTicks)
         xloc = plt.AutoLocator()
         # xloc = plt.LinearLocator(numticks=nXTicks)
         ax.xaxis.set_major_locator(xloc)
         if not frame:
             ax.spines['right'].set_visible(False)
             ax.spines['top'].set_visible(False)
             ax.get_xaxis().tick_bottom()
             ax.get_yaxis().tick_left()
         if xAxisRot:
             plt.setp(ax.get_xticklabels(), rotation='vertical')
         if AxisNameLong:
             if lang == 'EN':
                 if TextRender:
                     plt.ylabel(u'Membership $\\mu$')
                 elif not TextRender:
                     plt.ylabel(r'Membership \$\\mu\$')
             elif lang == 'DE':
                 if TextRender:
                     plt.ylabel(u'Zugehörigkeit $\\mu$')
                 elif not TextRender:
                     plt.ylabel(r'Zugeh\"origkeit \$\\mu\$')
         else:
             if TextRender:
                 h = plt.ylabel(u'$\\mu$')
             elif not TextRender:
                 h = plt.ylabel(r'\$\\mu\$')
             h.set_rotation(0)
         if xlabel == []:
             if lang == 'EN':
                 plt.xlabel(r'Value')
             elif lang == 'DE':
                 plt.xlabel(r'Wert')
         rcParams.update({'font.size': fontsize})
         # plt.tight_layout()
         self.Plot = plt
Esempio n. 11
0
#--------------------------------------------------------------
fig = Figure(figsize=(10, 6), facecolor='white')
#--------------------------------------------------------------
axis = fig.add_subplot(111)
axis.set_title("Graph plot of different vehicles and their count")
t0, = axis.plot(time, car)
t1, = axis.plot(time, bike)
t2, = axis.plot(time, bus)
t3, = axis.plot(time, cycle)
t4, = axis.plot(time, truck)
#axis.xticks(rotation=90)
axis.set_ylabel('COUNT')
axis.set_xlabel('TIME')
#axis.set_xticklabels(time, rotation=90, ha='right')
axis.xaxis.set_major_locator(plt.AutoLocator())
axis.grid()
fig.legend((t0, t1, t2, t3, t4), ('CAR', 'BIKE', 'BUS', 'CYCLE', 'TRUCK'),
           'upper right')


#--------------------------------------------------------------
def _destroyWindow():
    root.quit()
    root.destroy()


#--------------------------------------------------------------
root = tk.Tk()
root.withdraw()
root.protocol('WM_DELETE_WINDOW', _destroyWindow)
Esempio n. 12
0
def global_mayor_locator_auto(ax):
    ax.xaxis.set_major_locator(plt.AutoLocator())
    ax.yaxis.set_major_locator(plt.AutoLocator())
Esempio n. 13
0
def plot_trace_file(nodes=None, trace=''):
    # nodes: only plot specified nodes' trace data (list)
    # trace: [CWND, RCWND, RTT]

    figsize = tuple(map(lambda n: int(n), args.figsize.split(',')))
    figure = plt.figure(figsize=figsize)

    if not nodes: 
        nodes = ['1', '2', '3', '4', '5', '6']
        output_filename = trace + '.png'
    else:
        output_filename = '-'.join(['-'.join(nodes), trace + '.png'])

    if trace == 'MMWAVESINR':
        trace_filename = 'MmWaveSinrTime.txt'
        output_filename = 'MmWaveSinrTime.png'
    if trace == 'LTESINR':
        trace_filename = 'LteSinrTime.txt'
        output_filename = 'LteSinrTime.png'
    
    for i in nodes:
        if trace in ['CWND', 'RCWND', 'RTT', 'DATA']:   
            trace_filename = '-'.join([filename_base, i, i, 'TCP', trace + '.txt'])

        plot_style = 's' if trace == 'RCWND' else '-'

        x_vals, y_vals = [], []

        with open(trace_filename, 'r') as f:
            print("Opening ", trace_filename)
            for line in f:
                #time, old, new = re.match('([0-9\.]*)\W*([0-9\.]*)\W*([0-9\.]*)\W*')
                linedata = re.findall('([0-9\.]*)\W*', line)

                if trace == 'MMWAVESINR':
                    if linedata[1] != str(i):	# only gather current node's data
                        continue

                x_val, y_val = linedata[0], linedata[value_to_plot(trace)]                    

                if trace == 'CWND' or trace == 'RCWND':     # cwnd size to packets
                    y_val = str(int(int(y_val) / int(packet_size)))

                if '.' in x_val: 
                    x_vals.append(float(x_val))
                else:
                    x_vals.append(int(x_val))
                if '.' in y_val: 
                    y_vals.append(float(y_val))
                else:
                    y_vals.append(int(y_val))

        if trace == 'DATA': 
            (x_vals, y_vals) = data_trace(x_vals, y_vals)

        plt.plot(x_vals, y_vals, colors[int(i)-1]+plot_style, linewidth=0.5, antialiased=False, label='Flow '+i)
        #plt.plot(x_vals, y_vals, colors[int(i)-1], linestyle='s', markersize=2, linewidth=0.3, antialiased=False, label='Node '+i)
        
        plt.xlabel('time (s)')
        if trace == 'CWND' or trace == 'RCWND':
            plt.ylabel('CWND size (packets)')
        if trace == 'RTT':
            plt.ylabel('RTT (s)')
        if trace == 'DATA': 
            plt.ylabel('Throughput (Mb/s)')
        if trace == 'MMWAVESINR':
            plt.ylabel('SINR (dB)')
        if trace == 'LTESINR':
            plt.ylabel('SINR')
        #plt.axis('tight')
        '''if len(nodes) == 1:
            plt.title('Node {} {}'.format(nodes[0], trace))
        elif len(nodes) == 6:
            plt.title('All nodes {}'.format(trace))
        elif len(nodes) > 1:
            plt.title('Nodes {} {}'.format(', '.join(nodes), trace))
        else:
            plt.title('Node 1-6 {}'.format(trace))
        if trace == 'DATA': 
            plt.suptitle('Data throughput')
            plt.title('interval = ' + str(data_wndw) + ' s')'''

    ax = plt.axes()
    #ax.xaxis.set_major_locator(plt.MaxNLocator(5))
    #ax.yaxis.set_major_locator(plt.MaxNLocator(5))
    ax.xaxis.set_major_locator(plt.AutoLocator())
    ax.yaxis.set_major_locator(plt.AutoLocator())
    ax.legend()

    #plt.show()
    if not os.path.isdir('png'): os.makedirs('png')
    plt.savefig('./png/' + output_filename, bbox_inches='tight')