Beispiel #1
0
    def plot_curvature(self, Nx_per_patch, Ny_per_patch):
        """
        Plots the curvature of the surface.
        """
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_zlabel('z')

        # Get all the curvatures
        curvatures = []
        for patch in self:
            curvatures.append(
                patch.evaluate_abs_curvature(Nx_per_patch, Ny_per_patch))

        # Map the curvatures to colors
        norm = col.Normalize(vmin=np.amin(curvatures),
                             vmax=np.amax(curvatures))
        cmap = cm.Spectral_r(norm(curvatures))

        # Plot every patch with their colors
        for patch, colors in zip(self, cmap):
            patch.draw_to(ax, 30, 30, facecolors=colors)

        # add colorbar
        m = cm.ScalarMappable(cmap=cm.Spectral_r, norm=norm)
        m.set_array(curvatures)
        fig.colorbar(m)

        plt.show()
Beispiel #2
0
def plot_flow(od_matrix, title, chengdu):
    colors = [cm.Spectral_r(x) for x in linspace(0, 1, 5)]
    df = od_matrix.copy()
    df_class = mpc.NaturalBreaks(df['ridership'])
    df['class'] = df_class.yb
    bins = df_class.bins
    fig, ax = plt.subplots(1, 1, figsize=(5, 5))
    chengdu.plot(figsize=(5, 5),
                 facecolor='none',
                 edgecolor='black',
                 linewidth=0.6,
                 ax=ax,
                 alpha=1)
    for i in range(len(bins)):
        sub = df[df['class'] == i]
        for j in sub.index:
            ax.annotate('',
                        xy=(sub.loc[j, 'ori_x'], sub.loc[j, 'ori_y']),
                        xytext=(sub.loc[j, 'end_x'], sub.loc[j, 'end_y']),
                        arrowprops=dict(arrowstyle="->",
                                        color=colors[i],
                                        linewidth=0.5,
                                        alpha=0.8,
                                        shrinkA=0,
                                        shrinkB=0,
                                        patchA=None,
                                        patchB=None,
                                        connectionstyle='arc3,rad=-0.3'))
    ax.set_title(title, fontsize=16)
    ax.set_xlim(103.89, 104.24)
    ax.set_ylim(30.54, 30.8)
    line1, _ = ax.plot(((0, 0), (1, 1)), color=colors[0], alpha=0.8)
    line2, _ = ax.plot(((0, 0), (1, 1)), color=colors[1], alpha=0.8)
    line3, _ = ax.plot(((0, 0), (1, 1)), color=colors[2], alpha=0.8)
    line4, _ = ax.plot(((0, 0), (1, 1)), color=colors[3], alpha=0.8)
    line5, _ = ax.plot(((0, 0), (1, 1)), color=colors[4], alpha=1)
    plt.legend((line1, line2, line3, line4, line5), [
        '{} - {}'.format(0.0, round(bins[0], 1)), '{} - {}'.format(
            round(bins[0], 1), round(bins[1], 1)), '{} - {}'.format(
                round(bins[1], 1), round(bins[2], 1)), '{} - {}'.format(
                    round(bins[2], 1), round(bins[3], 1)), '{} - {}'.format(
                        round(bins[3], 1), round(bins[4], 1))
    ],
               framealpha=1,
               title='Trips',
               facecolor='whitesmoke')
    plt.xticks([])
    plt.yticks([])
    # plt.savefig(name, dpi=300, transparent=True, pad_inches=0)
    # plt.close(fig=fig)
    plt.show()
Beispiel #3
0
def get_image():
    x_bounds = (-123, -121)
    y_bounds = (37, 39)

    gdf = gpd.read_file("data/ca_nvda_grav.geojson")

    gdf_subset = gdf[(gdf["latitude"] > y_bounds[0])
                     & (gdf["latitude"] < y_bounds[1]) &
                     (gdf["longitude"] > x_bounds[0]) &
                     (gdf["longitude"] < x_bounds[1])]
    coord_list = list(zip(gdf_subset.geometry.x, gdf_subset.geometry.y))

    grid_1 = interpolate_2d(coord_list,
                            gdf_subset["isostatic_anom"].values,
                            x_bounds=x_bounds,
                            y_bounds=y_bounds)

    ## convert to colormap image
    im = Image.fromarray(np.uint8(cm.Spectral_r(grid_1) * 255))
    return im
Beispiel #4
0
def Shape(geometry,
          diel,
          d,
          iteration=-1,
          position="./",
          decimal=0,
          FullLattice=False):
    """Plot the shape of object as dot matrix.
    #Input:
    # --SC                                                         SolutionClass
    #   Solution Class.
    # --FullLattice   Boolean
    #   If true. Geometry is a full n*n*n matrix. diel=0 for point seen as air.
    """
    #d = SC.Get_d()
    N = round(np.shape(geometry)[0] / 3)
    if (N != np.shape(diel)[0] / 3):
        print("size not equal!")
    geometry = np.reshape(geometry, (N, 3))
    #geometry = SC.Get_geometry()
    for i in range(3):
        geometry[:, i] -= np.amin(geometry[:, i])
    [X, Y, Z] = map(int, list(np.amax(geometry, axis=0) + 1))
    Axis_max = max(X, Y, Z) * 1.2 * d

    diel = np.reshape(diel, (N, 3))
    diel = diel[:, 0]
    #diel = SC.Get_diel()[:,0]

    cmaparg = 'Spectral_r'
    minn, maxx = 0, 1
    norm = matplotlib.colors.Normalize(minn, maxx)
    colorset = cm.ScalarMappable(norm=norm, cmap=cmaparg)
    colorset.set_array([])
    if FullLattice:
        index = np.where(diel > 0.5)
        diel = diel[index]
        geometry = geometry[index]
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    geo_dic = set()
    surf_list = []
    surf_color = []
    x_grid, y_grid, z_grid = (np.indices((X + 1, Y + 1, Z + 1)) - 0.5) * d
    filled, colors = np.zeros((X, Y, Z)), np.zeros((X, Y, Z))
    for i, pos in enumerate(geometry):
        geo_dic.add((pos[0], pos[1], pos[2]))
    for i, pos in enumerate(geometry):
        if (pos[0]+1,pos[1],pos[2]) not in geo_dic or (pos[0]-1,pos[1],pos[2]) not in geo_dic or\
           (pos[0],pos[1]+1,pos[2]) not in geo_dic or (pos[0],pos[1]-1,pos[2]) not in geo_dic or\
           (pos[0],pos[1],pos[2]+1) not in geo_dic or (pos[0],pos[1],pos[2]-1) not in geo_dic:
            filled[pos[0], pos[1], pos[2]] = 1
            colors[pos[0], pos[1], pos[2]] = diel[i]
    surf_list = np.array(surf_list)
    surf_color = np.array(surf_color)
    # print(x_grid.shape,y_grid.shape,z_grid.shape,filled.shape,colors.shape)
    colors = cm.Spectral_r(norm(colors))
    ln = ax.voxels(x_grid,
                   y_grid,
                   z_grid,
                   filled.astype(bool),
                   facecolors=colors,
                   edgecolor='white',
                   linewidth=0.2)
    #ax2.scatter(geometry[:,0]*d,geometry[:,1]*d,geometry[:,2]*d,c=E_tot_abs, s=15, cmap=cmaparg)
    ax.set_xlim(-(Axis_max - X * d) / 2, (Axis_max + X * d) / 2)
    ax.set_ylim(-(Axis_max - Y * d) / 2, (Axis_max + Y * d) / 2)
    ax.set_zlim(-(Axis_max - Z * d) / 2, (Axis_max + Z * d) / 2)
    ax.set_xlabel("x[nm]")
    ax.set_ylabel("y[nm]")
    ax.set_zlabel("z[nm]")
    ax.grid(False)
    fig.colorbar(colorset, shrink=0.9, aspect=10)

    #plt.show()
    #plt.savefig("./optimization_geometries/Iteration{}.png".format(it))
    if iteration == -1:
        plt.savefig("Space.png")
    else:
        fig.suptitle("iteration{}".format(iteration))
        plt.savefig(position +
                    "{}Space.png".format(str(iteration).zfill(decimal)))
Beispiel #5
0
def EField(geometry,
           diel,
           d,
           wl,
           k_dir,
           E_dir,
           E_tot,
           iteration=-1,
           position="./",
           decimal=0,
           FullLattice=False):
    """Plot the E field of object as arrow matrix.
    # Input:
    # --SC         SolutionClass
    #   Solved Solution Class.
    # --idx1,idx2  int
    #   Indexs of the target instance.
    """
    #print(geometry)

    N = round(np.shape(geometry)[0] / 3)
    #print(N)
    geometry = np.reshape(geometry, (N, 3))

    print(geometry.shape)
    #diel=np.reshape(diel,(N,3))
    #diel=diel[:,0]

    for i in range(3):
        geometry[:, i] -= np.amin(geometry[:, i])

    #print(geometry)
    [X, Y, Z] = list(np.amax(geometry, axis=0) + 1)
    Axis_max = max(X, Y, Z) * 1.2 * d

    E_tot = E_tot.reshape(int(E_tot.size / 3), 3)
    E_tot_abs = np.abs(np.sqrt(np.sum((E_tot)**2, axis=1)))
    """
    if FullLattice:
        index = np.where(diel!=0)                                      #disabled all codes with "diel"
        geometry = geometry[index]
        E_tot = E_tot[index]
        E_tot_abs = E_tot_abs[index]
    """
    cmaparg = 'Spectral_r'
    minn, maxx = E_tot_abs.min(), E_tot_abs.max()
    print(minn, maxx, np.argmax(E_tot_abs))
    norm = matplotlib.colors.Normalize(minn, maxx)
    colorset = cm.ScalarMappable(norm=norm, cmap=cmaparg)
    colorset.set_array([])

    fig1 = plt.figure()
    ax1 = fig1.add_subplot(111, projection='3d')
    ax1.quiver(geometry[:, 0] * d,
               geometry[:, 1] * d,
               geometry[:, 2] * d,
               np.real(E_tot[:, 0]),
               np.real(E_tot[:, 1]),
               np.real(E_tot[:, 2]),
               length=10,
               lw=1)
    ax1.set_xlim(-(Axis_max - X * d) / 2, (Axis_max + X * d) / 2)
    ax1.set_ylim(-(Axis_max - Y * d) / 2, (Axis_max + Y * d) / 2)
    ax1.set_zlim(-(Axis_max - Z * d) / 2, (Axis_max + Z * d) / 2)
    ax1.set_xlabel("x[nm]")
    ax1.set_ylabel("y[nm]")
    ax1.set_zlabel("z[nm]")
    ax1.grid(False)
    fig1.suptitle("E field - Arrow plot\n {}nm, {}".format(wl, E_dir))
    fig2 = plt.figure()
    ax2 = fig2.add_subplot(111, projection='3d')
    geo_dic = set()
    surf_list = []
    surf_color = []
    x_grid, y_grid, z_grid = (np.indices((X + 1, Y + 1, Z + 1)) - 0.5) * d
    filled, colors = np.zeros((X, Y, Z)), np.zeros((X, Y, Z))
    for i, pos in enumerate(geometry):
        geo_dic.add((pos[0], pos[1], pos[2]))
    for i, pos in enumerate(geometry):
        if (pos[0]+1,pos[1],pos[2]) not in geo_dic or (pos[0]-1,pos[1],pos[2]) not in geo_dic or\
           (pos[0],pos[1]+1,pos[2]) not in geo_dic or (pos[0],pos[1]-1,pos[2]) not in geo_dic or\
           (pos[0],pos[1],pos[2]+1) not in geo_dic or (pos[0],pos[1],pos[2]-1) not in geo_dic:
            filled[pos[0], pos[1], pos[2]] = 1
            colors[pos[0], pos[1], pos[2]] = E_tot_abs[i]
    surf_list = np.array(surf_list)
    surf_color = np.array(surf_color)

    colors = cm.Spectral_r(norm(colors))
    ax2.voxels(x_grid,
               y_grid,
               z_grid,
               filled.astype(bool),
               facecolors=colors,
               linewidth=0.5)

    ax2.set_xlim(-(Axis_max - X * d) / 2, (Axis_max + X * d) / 2)
    ax2.set_ylim(-(Axis_max - Y * d) / 2, (Axis_max + Y * d) / 2)
    ax2.set_zlim(-(Axis_max - Z * d) / 2, (Axis_max + Z * d) / 2)
    ax2.set_xlabel("x[nm]")
    ax2.set_ylabel("y[nm]")
    ax2.set_zlabel("z[nm]")
    ax2.grid(False)
    fig2.colorbar(colorset, shrink=0.9, aspect=10)
    if iteration == -1:
        fig2.suptitle("E field - Scatter plot\n {}nm, {}".format(wl, k_dir))
        plt.savefig("E_field.png")
    else:
        fig2.suptitle("E field - Scatter plot\n {}nm, {} - iteration{}".format(
            wl, k_dir, iteration))
        plt.savefig(position +
                    "{}E_field.png".format(str(iteration).zfill(decimal)))
Beispiel #6
0
def draw_areachart(Num_Date):
    Span_Date = 180
    ax.clear()
    if Num_Date < Span_Date:
        df_temp = df.loc[0:Num_Date, :]
        df_span = df.loc[0:Span_Date, :]
        colors = cm.Spectral_r(df_span.price.values /
                               float(max(df_span.price.values)))
        plt.bar(df_temp.date.values,
                df_temp.price.values,
                color=colors,
                width=1.5,
                align="center",
                zorder=1)
        plt.plot(df_temp.date, df_temp.price, color='k', zorder=2)
        plt.scatter(df_temp.date.values[-1],
                    df_temp.price.values[-1],
                    color='white',
                    s=150,
                    edgecolor='k',
                    linewidth=2,
                    zorder=3)
        plt.text(df_temp.date.values[-1],
                 df_temp.price.values[-1] * 1.18,
                 s=np.round(df_temp.price.values[-1], 1),
                 size=10,
                 ha='center',
                 va='top')
        plt.ylim(0, df_span.price.max() * 1.68)
        plt.xlim(df_span.date.values[0], df_span.date.values[-1])
        plt.xticks(ticks=df_span.date.values[0:Span_Date + 1:30],
                   labels=df_span.date.values[0:Span_Date + 1:30],
                   rotation=0,
                   fontsize=9)
    else:
        df_temp = df.loc[Num_Date - Span_Date:Num_Date, :]
        colors = cm.Spectral_r(df_temp.price / float(max(df_temp.price)))
        plt.bar(df_temp.date.values[:-2],
                df_temp.price.values[:-2],
                color=colors[:-2],
                width=1.5,
                align="center",
                zorder=1)
        plt.plot(df_temp.date[:-2], df_temp.price[:-2], color='k', zorder=2)
        plt.scatter(df_temp.date.values[-4],
                    df_temp.price.values[-4],
                    color='white',
                    s=150,
                    edgecolor='k',
                    linewidth=2,
                    zorder=3)
        plt.text(df_temp.date.values[-1],
                 df_temp.price.values[-1] * 1.18,
                 s=np.round(df_temp.price.values[-1], 1),
                 size=10,
                 ha='center',
                 va='top')
        plt.ylim(0, df_temp.price.max() * 1.68)
        plt.xlim(df_temp.date.values[0], df_temp.date.values[-1])
        plt.xticks(ticks=df_temp.date.values[0:Span_Date + 1:30],
                   labels=df_temp.date.values[0:Span_Date + 1:30],
                   rotation=0,
                   fontsize=9)

    plt.margins(x=0.2)
    ax.spines['top'].set_color('none')  # 设置上‘脊梁’为红色
    ax.spines['right'].set_color('none')  # 设置上‘脊梁’为无色
    ax.spines['left'].set_color('none')  # 设置上‘脊梁’为无色
    plt.grid(axis="y", c=(217 / 256, 217 / 256, 217 / 256),
             linewidth=1)  # 设置网格线
    plt.text(0.01,
             0.95,
             "BTC平均价格($)",
             transform=ax.transAxes,
             size=10,
             weight='light',
             ha='left')
    ax.text(-0.07,
            1.03,
            '2013年到2021年的比特币BTC价格变化情况',
            transform=ax.transAxes,
            size=17,
            weight='light',
            ha='left')
Beispiel #7
0
ax.spines['top'].set_color('none')  # 设置上‘脊梁’为无色
ax.spines['right'].set_color('none')  # 设置上‘脊梁’为无色
ax.spines['left'].set_color('none')  # 设置上‘脊梁’为无色
plt.grid(axis="y", c=(217 / 256, 217 / 256, 217 / 256), linewidth=1)  # 设置网格线
plt.show()
"""
Span设定的是多少天的价格,这里使用200天。N_Span代表权重;
df_temp=df.loc[N_Span*Span:(N_Span+1)*Span,:]代表的是选择到179行为止的数据,即180天。
plt.fill_between()是使用单色--红色填充,
"""
# 4.2 渐变颜色面积图
Span_Date = 180
Num_Date = 360  # 终止日期
df_temp = df.loc[Num_Date - Span_Date:
                 Num_Date, :]  # 选择从Num_Date-Span_Date开始到Num_Date的180天的数据
colors = cm.Spectral_r(df_temp.price / float(max(df_temp.price)))
fig = plt.figure(figsize=(6, 4), dpi=100)
plt.subplots_adjust(top=1, bottom=0, left=0, right=0.9, hspace=0, wspace=0)
plt.bar(df_temp.date.values,
        df_temp.price.values,
        color=colors,
        width=1,
        align="center",
        zorder=1)
plt.plot(df_temp.date, df_temp.price, color='k', zorder=2)
plt.scatter(df_temp.date.values[-1],
            df_temp.price.values[-1],
            color='white',
            s=150,
            edgecolor='k',
            linewidth=2,
Beispiel #8
0
ax.xaxis.pane.fill = False
ax.yaxis.pane.fill = False
ax.zaxis.pane.fill = False
ax.xaxis.pane.set_edgecolor('k')
ax.yaxis.pane.set_edgecolor('k')
ax.zaxis.pane.set_edgecolor('k')


dz=hist.ravel()
zpos = 0

# Construct arrays with the dimensions for the 16 bars.
dx = dy = 0.5 * np.ones_like(zpos)
dz = hist.ravel()

colors = cm.Spectral_r(dz / float(max(dz)))

ax.bar3d(XX.ravel(), YY.ravel(), zpos, 0.3, 0.3, dz, zsort='average',color=colors,
         alpha=1,edgecolor='k',linewidth=0.2)

ax.set_xlabel( "x axis")
ax.set_ylabel("y axis")
ax.set_zlabel("count")

ax2 = fig.add_axes([0.85, 0.35, 0.025, 0.3])
cmap = mpl.cm.Spectral_r
norm = mpl.colors.Normalize(vmin=0, vmax=1)
bounds = np.arange(min(dz),max(dz),20)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap,norm=norm,boundaries=bounds,
ticks=np.arange(min(dz),max(dz),20),spacing='proportional',label='count')
         linestyle='-',
         linewidth='0.5',
         color='gray',
         alpha=0.5)

N = df.shape[0]

x_angles = [n / float(N) * 2 * np.pi for n in range(N)]
#x_angles += x_angles[:1]

upperlimits = (df['max.temperaturec'] - df['min.temperaturec']).values
#upperlimits += upperlimits[:1]
lowerlimits = df['min.temperaturec'].values
#lowerlimits += lowerlimits[:1]

colors = cm.Spectral_r(upperlimits / float(max(upperlimits)))

#ax.bar(x_angles,lowerlimits, color='none',edgecolor='none',width=0.01,alpha=1)
#ax.bar(x_angles,upperlimits, color=colors,edgecolor='none',width=0.02, bottom=lowerlimits,alpha=1)

ax.bar(x_angles,
       lowerlimits,
       color='none',
       edgecolor='none',
       width=0.01,
       alpha=1)
ax.bar(x_angles,
       upperlimits,
       color=colors,
       edgecolor='none',
       width=0.02,