예제 #1
0
    def gauge_plot(arrow_index, labels):

        list_colors = np.linspace(0, 1, int(len(labels) / 2))
        size_of_groups = np.ones(len(labels))

        white_half = np.ones(len(list_colors)) * .5
        color_half = list_colors

        cs1 = cm.RdYlGn_r(color_half)
        cs2 = cm.seismic(white_half)
        cs = np.concatenate([cs1, cs2])

        fig, ax = plt.subplots()

        ax.pie(size_of_groups, colors=cs, labels=labels)

        my_circle = plt.Circle((0, 0), 0.6, color='white')
        ax.add_artist(my_circle)

        arrow_angle = (arrow_index / float(len(list_colors))) * 3.14159
        arrow_x = 0.8 * math.cos(arrow_angle)
        arrow_y = 0.8 * math.sin(arrow_angle)
        arr = plt.arrow(0,0,-arrow_x,arrow_y, width=.02, head_width=.05, \
            head_length=.1, fc='k', ec='k')

        ax.add_artist(arr)
        ax.add_artist(plt.Circle((0, 0), radius=0.04, facecolor='k'))
        ax.add_artist(plt.Circle((0, 0), radius=0.03, facecolor='w',
                                 zorder=11))

        ax.set_aspect('equal')

        st.pyplot(fig)

        return True
예제 #2
0
def ledMetars(strip, df, stat, i):
    strip.setPixelColorRGB(0, int(cm.RdYlGn_r(stat)[0] * 255),
                           int(colorMapStat(stat)[1] * 255),
                           int(colorMapStat(stat)[2] * 255))
    print('UPDATE: ' + str(i) + ', LED: ' + '0' + ', SID: ' + str(stat) +
          ', DATA: ' + 'status' + ', COLOR: ' + str([
              int(colorMapStat(stat)[1] * 255),
              int(colorMapStat(stat)[0] * 255),
              int(colorMapStat(stat)[2] * 255)
          ]))
    if stat == float(1):
        for led in df.index:
            r = df['R'][led]
            g = df['G'][led]
            b = df['B'][led]
            station = df['station_id'][led]
            data = df[dataUse][led]
            try:
                strip.setPixelColorRGB(int(led), int(r * 255), int(g * 255),
                                       int(b * 255))
            except:
                strip.setPixelColorRGB(int(led), 0, 0, 0)
            print('UPDATE: ' + str(i) + ', LED: ' + str(led) + ', SID: ' +
                  str(station) + ', DATA: ' + str(data) + ', COLOR: [' +
                  str(r * 255) + ',' + str(g * 255) + ',' + str(b * 255) + ']')
    strip.show()
예제 #3
0
def ledMetars(strip, f, stat, i, update):
    strip.setPixelColor(
        0,
        Color(int(cm.RdYlGn_r(stat)[1] * 255),
              int(colorMapStat(stat)[0] * 255),
              int(colorMapStat(stat)[2] * 255)))
    strip.show()
    print('UPDATE: ' + str(i) + ', LED: ' + '0' + ', SID: ' + 'status' +
          ', DATA: ' + 'status' + ', COLOR: ' + str([
              int(colorMapStat(stat)[1] * 255),
              int(colorMapStat(stat)[0] * 255),
              int(colorMapStat(stat)[2] * 255)
          ]))
    if update == 'true':
        for id in df.index:
            if df['led'][id] > 0:
                if df['R'][id] > -1:
                    strip.setPixelColor(
                        int(df['led'][id]),
                        Color(int(df['G'][id] * 255), int(df['R'][id] * 255),
                              int(df['B'][id] * 255)))
                    strip.show()
                    if ledVerbose:
                        print('UPDATE: ' + str(i) + ', LED: ' +
                              str(df['led'][id]) + ', SID: ' +
                              str(df['station_id'][id]) + ', DATA: ' +
                              str(df[dataUse][id]) + ', COLOR: ' +
                              str(df['clr255'][id]))
def plot(data, fname='lifecycle-carbon-emissions-nolabel.png'):
    labels, values = zip(*reversed(sorted(data['val'].items(), 
                                          key=lambda kv: kv[1][1])))
    labels = [label.capitalize() for label in labels]
    values = np.array(values)[:,1]
    width = 0.35
    index = np.arange(len(labels))

    fig, ax = plt.subplots(dpi=300)
    # _r is for reversed colormap :)
    colors = cm.RdYlGn_r(values/100.0)
    bars = ax.bar(index, values, width, color=colors, edgecolor="k")
    #bars = ax.bar(index, values, width)

    plt.title(data['title'])
    ax.set_ylabel('Lifecycle emissions ({})'.format(data['units']))
    ax.set_xticks(index)
    ax.set_xticklabels(labels)
    ax.grid(alpha=0.7, linestyle='--', axis='y')
    # ha needed or else labels rotate on center
    plt.xticks(rotation=50, ha="right")
    ax.set_ylim([0,900]) # make room for data label

    # Add data labels on each bar
    for bar in bars:
        height = bar.get_height()
        ax.annotate('{:.0f}'.format(height),
                    xy=(bar.get_x() + bar.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom', size=6)
    
    # Point out nuclear
    ann = ax.annotate("Nuclear is among\nthe lowest-carbon forms\nof energy we know",
                  xy=(11, 70), xycoords='data',
                  xytext=(8, 500), textcoords='data',
                  size=12, va="center", ha="center",
                  bbox=dict(boxstyle="round4", fc="w"),
                  arrowprops=dict(arrowstyle="-|>",
                                  connectionstyle="arc3,rad=-0.2",
                                  fc="w"),
                  )
    #plt.tight_layout()
    # Manually squish the subplot to make room for labels
    #fig.subplots_adjust(bottom=0.4,top=0.90)
    fig.subplots_adjust(bottom=0.3,top=0.90)
    #ann = ax.text(0.1, 0.1, '\n'.join(textwrap.wrap(data['ref'] + ". Plot by whatisnuclear.com.",130)),
    #              size=6, va="center", ha="left", transform=fig.transFigure
    #              )


    if fname:
        plt.savefig(fname)
    else:
        plt.show()
예제 #5
0
def plot_cumulative_returns_by_quantile(quantile_returns, period=1, ax=None):
    """
    Plots the cumulative returns of various factor quantiles.

    Parameters
    ----------
    quantile_returns : pd.DataFrame
        Cumulative returns by factor quantile.
    period: int, optional
        Period over which the daily returns are calculated 
    ax : matplotlib.Axes, optional
        Axes upon which to plot.

    Returns
    -------
    ax : matplotlib.Axes
    """

    if ax is None:
        f, ax = plt.subplots(1, 1, figsize=(18, 6))

    ret_wide = quantile_returns.reset_index()\
        .pivot(index='date', columns='quantile', values=period)

    if period > 1:
        daily_returns = lambda ret, period: (np.nanmean(ret)**
                                             (1. / period)) - 1
        period_ret_wide = ret_wide.add(1)**period
        ret_wide = pd.rolling_apply(period_ret_wide,
                                    period,
                                    daily_returns,
                                    min_periods=1,
                                    args=(period, ))

    cum_ret = ret_wide.add(1).cumprod()
    cum_ret = cum_ret.loc[:, ::-1]
    num_quant = len(cum_ret.columns)

    colors = cm.RdYlGn_r(np.linspace(0, 1, num_quant))

    cum_ret.plot(lw=2, ax=ax, color=colors)
    ax.legend()
    ymin, ymax = cum_ret.min().min(), cum_ret.max().max()
    ax.set(ylabel='Log Cumulative Returns',
           title='Cumulative Return by Quantile ({} Period Forward Return)'.
           format(period),
           xlabel='',
           yscale='symlog',
           yticks=np.linspace(ymin, ymax, 5),
           ylim=(ymin, ymax))

    ax.yaxis.set_major_formatter(ScalarFormatter())
    ax.axhline(1.0, linestyle='-', color='black', lw=1)

    return ax
def plot_bar(seq=None, shape_ls=None, colormap='RdYlGn_r', savefn=None):
    if shape_ls is None:
        shape_ls = [random.random() for i in range(len(seq))]
    shape_ls = np.array(shape_ls)
    if colormap == 'RdYlGn_r':
        colors = cm.RdYlGn_r(shape_ls, )
        plot = plt.scatter(shape_ls, shape_ls, c = shape_ls, cmap = colormap)
        plt.clf()
        plt.colorbar(plot)
        
    plt.bar(range(len(shape_ls)), shape_ls, color = colors)
    plt.xticks(range(len(seq)), list(seq))
    plt.tight_layout()
    plt.savefig(savefn)
    plt.close()
예제 #7
0
def plot_quantile_average_cumulative_return(avg_cumulative_returns,
                                            by_quantile=False,
                                            std_bar=False,
                                            title=None,
                                            ax=None):
    """
    Plots sector-wise mean daily returns for factor quantiles
    across provided forward price movement columns.

    Parameters
    ----------
    avg_cumulative_returns: pd.Dataframe
        The format is the one returned by
        performance.average_cumulative_return_by_quantile
    by_quantile : boolean, optional
        Disaggregated figures by quantile (useful to clearly see std dev bars)
    std_bar : boolean, optional
        Plot standard deviation plot
    title: string, optional
        Custom title
    ax : matplotlib.Axes, optional
        Axes upon which to plot.

    Returns
    -------
    ax : matplotlib.Axes
    """

    avg_cumulative_returns = avg_cumulative_returns.multiply(DECIMAL_TO_BPS)
    quantiles = len(avg_cumulative_returns.index.levels[0].unique())
    palette = [cm.RdYlGn_r(i) for i in np.linspace(0, 1, quantiles)]

    if by_quantile:

        if ax is None:
            v_spaces = ((quantiles - 1) // 2) + 1
            f, ax = plt.subplots(v_spaces,
                                 2,
                                 sharex=False,
                                 sharey=False,
                                 figsize=(18, 6 * v_spaces))
            ax = ax.flatten()

        for i, (quantile, q_ret) in enumerate(
                avg_cumulative_returns.groupby(level='factor_quantile')):

            mean = q_ret.loc[(quantile, 'mean')]
            mean.name = 'Quantile ' + str(quantile)
            mean.plot(ax=ax[i], color=palette[i])
            ax[i].set_ylabel('Mean Return (bps)')

            if std_bar:
                std = q_ret.loc[(quantile, 'std')]
                ax[i].errorbar(std.index,
                               mean,
                               yerr=std,
                               fmt=None,
                               ecolor=palette[i],
                               label=None)

            ax[i].axvline(x=0, color='k', linestyle='--')
            ax[i].legend()
            i += 1

    else:

        if ax is None:
            f, ax = plt.subplots(1, 1, figsize=(18, 6))

        for i, (quantile, q_ret) in enumerate(
                avg_cumulative_returns.groupby(level='factor_quantile')):

            mean = q_ret.loc[(quantile, 'mean')]
            mean.name = 'Quantile ' + str(quantile)
            mean.plot(ax=ax, color=palette[i])

            if std_bar:
                std = q_ret.loc[(quantile, 'std')]
                ax.errorbar(std.index,
                            mean,
                            yerr=std,
                            fmt=None,
                            ecolor=palette[i],
                            label='none')
            i += 1

        ax.axvline(x=0, color='k', linestyle='--')
        ax.legend()
        ax.set(ylabel='Mean Return (bps)',
               title=("Average Cumulative Returns by Quantile"
                      if title is None else title),
               xlabel='Periods')

    return ax
예제 #8
0
#-----------------------
# RMSD w.r.t 1ake vs RMSD w.r.t 4ake plot
#-----------------------
print "\t2D CV"

#-- create figure ------
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
ax.set_aspect(1)

#-- plot data ----------
ax.scatter(ref_rmsd, 0, marker="*", s=100, label="4ake", c='cyan')
ax.scatter(0, ref_rmsd, marker="x", s=80, label="1ake", c='magenta')
if multicolor:
	colors = cm.RdYlGn_r( 1.0*time/np.max(time) )
	ax.scatter(trj_rmsd[:,0], trj_rmsd[:,1], c=colors, s=ss, \
	    edgecolor='black', linewidth=0.2)
else:
	ax.scatter(trj_rmsd[:,0], trj_rmsd[:,1], c='blue', s=ss, \
	  edgecolor='none')

#-- plot settings ------
ax.tick_params(axis='both', which='major', labelsize=16)
ax.grid(True)

#-- labels/legend ------
ax.set_ylabel(r'$\Delta$RMSD from 4ake ($\AA$)', fontsize=20)
ax.set_xlabel(r'$\Delta$RMSD from 1ake ($\AA$)', fontsize=20)
ax.set_title(r'$\Delta$RMSD from End Structures (1ake vs 4ake) -- '+adk+' trj'+postfix)
예제 #9
0
def plot_quantile_average_cumulative_return(avg_cumulative_returns,
                                            by_quantile=False,
                                            std_bar=False,
                                            ax=None,
                                            periods_before='',
                                            periods_after=''):

    avg_cumulative_returns = avg_cumulative_returns.multiply(DECIMAL_TO_BPS)
    quantiles = len(avg_cumulative_returns.index.levels[0].unique())
    palette = [cm.RdYlGn_r(i) for i in np.linspace(0, 1, quantiles)]

    if by_quantile:

        if ax is None:
            v_spaces = ((quantiles - 1) // 2) + 1
            f, ax = plt.subplots(v_spaces,
                                 2,
                                 sharex=False,
                                 sharey=False,
                                 figsize=(18, 6 * v_spaces))
            ax = ax.flatten()

        for i, (quantile, q_ret) in enumerate(
                avg_cumulative_returns.groupby(level='factor_quantile')):

            mean = q_ret.loc[(quantile, 'mean')]
            mean.name = AVGCUMRET.get("COLUMN").format(quantile)
            mean.plot(ax=ax[i], color=palette[i])
            ax[i].set_ylabel(AVGCUMRET.get("YLABEL"))

            if std_bar:
                std = q_ret.loc[(quantile, 'std')]
                ax[i].errorbar(std.index,
                               mean,
                               yerr=std,
                               fmt='none',
                               ecolor=palette[i],
                               label=None)

            ax[i].axvline(x=0, color='k', linestyle='--')
            ax[i].legend()
            i += 1

    else:

        if ax is None:
            f, ax = plt.subplots(1, 1, figsize=(18, 6))

        for i, (quantile, q_ret) in enumerate(
                avg_cumulative_returns.groupby(level='factor_quantile')):

            mean = q_ret.loc[(quantile, 'mean')]
            mean.name = AVGCUMRET.get("COLUMN").format(quantile)
            mean.plot(ax=ax, color=palette[i])

            if std_bar:
                std = q_ret.loc[(quantile, 'std')]
                ax.errorbar(std.index,
                            mean,
                            yerr=std,
                            fmt='none',
                            ecolor=palette[i],
                            label=None)
            i += 1

        ax.axvline(x=0, color='k', linestyle='--')
        ax.legend()
        ax.set(
            title=AVGCUMRET.get("YLABEL").format(periods_before,
                                                 periods_after),
            xlabel=AVGCUMRET.get("XLABEL"),
            ylabel=AVGCUMRET.get("YLABEL"),
        )

    return ax
예제 #10
0
    values = np.mat(values)

    ax = plt.subplot(projection='3d')
    #mns, avr, tcx, met, _ = prepare_averages(simulations)

    top = np.ravel(values)
    X = len(scales)
    Y = len(methods)
    xx = [[i] * X for i in range(Y)]
    yy = [i for i in range(X)] * Y
    xx = np.ravel(xx)
    #top = np.log10(top)*10
    mx = np.max(values)
    mn = np.min(values)
    alpha = 0.7
    color_mapping = [cm.RdYlGn_r((i - mn) / (mx - mn)) for i in top]
    color_mapping = [(r, g, b, alpha) for r, g, b, a in color_mapping]

    ax.bar3d(xx, yy, np.zeros_like(top), 0.9, 0.9, top, color=color_mapping)
    for i in range(len(top)):
        text = to_si(top[i] * 1e-9)
        ax.text3D(xx[i] + 0.5,
                  yy[i] + 0.5,
                  top[i] + 1,
                  text,
                  horizontalalignment='center')

    # ax.set_zscale('log')
    ax.set_xlabel("")
    #ax.set_xlim(0,max(len(methods), len(scales)))
    ax.set_xticks([i + 0.5 for i in range(len(methods))])