Esempio n. 1
0
def plot_zipcode_heatmap(ax, zip_vals, default_color='white', border=1):
    for zip_i, zip_row in zipcodeshapes.iterrows():
        z = int(zip_i)
        points = np.array(zip_row['points'])
        if z in zip_vals:
            v = zip_vals[z]
            if len(points) > 0:
                print points
                patch = pylab.Polygon(points , closed=True, fill=True, color=v)
                ax.add_patch(patch)
        else:
            if len(points) > 0:
                patch = pylab.Polygon(points , closed=True, fill=True, facecolor=default_color, linewidth=border, edgecolor='k')
                ax.add_patch(patch)     
Esempio n. 2
0
def polygon(x, y=None, normal=False, fill=True, **kwargs):
    oline = kwargs.pop('outline', False)
    outline_prop = kwargs.pop('outline_prop', {})
    tmp = dict(
        color='0.2',
        alpha=0.4,
        linewidth=2,
    )

    ax = pylab.gca()
    if normal:
        tmp['transform'] = ax.transAxes

    if y is not None:
        x = np.array(zip(x, y))

    if oline or (not fill):
        tmp['facecolor'] = 'none'
        tmp['edgecolor'] = kwargs.pop('color', tmp.pop('color'))

    tmp.update(kwargs)
    patch = pylab.Polygon(x, **tmp)

    if oline:
        outline(oatch, **outline_prop)

    ax.add_patch(patch)
    return patch
Esempio n. 3
0
def draw_env(wall_choords, holes_choords):
    plt.plot([x for x, y in wall_choords] + [0],
             [y for x, y in wall_choords] + [0],
             'black',
             alpha=0.125)
    for h in holes_choords:
        plt.gca().add_patch(plt.Polygon(h, fc='r', alpha=0.25))
Esempio n. 4
0
 def plot(self, index, ax=None, **kwargs):
     poly_options = dict(color='red', lw=2, ls='--', fill=False)
     poly_options.update(**kwargs)
     
     ax = ax or plt.gca()
     image = self.image(index)
     poly = self.polygon(index)
     ax.imshow(image)
     ax.add_patch(plt.Polygon(poly, **poly_options))
Esempio n. 5
0
def slide_7_2():
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3)
    circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)
    pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],
                       color='g',
                       alpha=0.5)
    ax.add_patch(rect)
    ax.add_patch(circ)
    ax.add_patch(pgon)
Esempio n. 6
0
            bin_av = bin_av + Jv_pde[i * resize_factor + j]
            Jv_coarse[i] = bin_av / resize_factor

#  pde_rho_sq = norm(rho_coarse)**2
    pde_Jv_sq = norm(Jv_coarse)**2

    log_flag = 'log'
    #  log_flag = 'linear'
    save_flag = False

    lines = ["-", "--", "-.", ":", "-", "--", "-.", ":", "-", "--", "-.", ":"]

    # points_o1a = [[1e-4, 1e-3], [1e-4, 5e-3], [5e-4, 5e-3]]
    points_o1b = [[1e-5, 1e-3], [1e-5, 5e-3], [5e-5, 5e-3]]
    # triangle_o1a = plt.Polygon(points_o1a, fill=None  ,edgecolor='r')
    triangle_o1b = plt.Polygon(points_o1b, fill=None, edgecolor='grey')

    #Plot RHO
    #   plot_rho =  plt.plot(rho_Dt_sde, '-', color='g', label = '$\$')
    #    plot_rho = plt.plot( rho_coarse, '--', color='r', label = '$\$')

    # plt.ylabel(r' $\rho$', fontsize = 16)
    #   plt.xlabel('$x$', fontsize = 16)
    #  plt.show()

    points_o1 = [[1e-5, 1e-3], [1e-5, 4e-3], [4e-5, 4e-3]]
    triangle_o1 = plt.Polygon(points_o1, fill=None, edgecolor='r')

    #
    #    for m in range (0,len(Mlist)):
    #        plot_var = plt.plot(Nlist_inv, (sde_rho_sq[m] -sq_E_rho[m])/bins, lines[m], label =r'$m=%d$' %Mlist[m] , linewidth=3)
Esempio n. 7
0
def add_arbitrary_plane(device_dictionary: dict, mins, maxs, axes, draw_axis):
    print("AXES:", axes)
    draw_axis.set_xlim(mins[axes[0]], maxs[axes[0]])
    draw_axis.set_ylim(maxs[axes[1]], mins[axes[1]])
    draw_axis.set_title(f"axes{axes[0]}{axes[1]} projection view")
    draw_axis.set_xlabel(f"{axes[0]}-axis [m]")
    draw_axis.set_ylabel(f"{axes[1]}-axis [m]")

    fov = device_dictionary["general"][MetadataDeviceTags.FIELD_OF_VIEW.tag]

    for detector in device_dictionary["detectors"]:
        if not (MetadataDeviceTags.DETECTOR_POSITION.tag
                in device_dictionary["detectors"][detector]
                and MetadataDeviceTags.DETECTOR_GEOMETRY.tag
                in device_dictionary["detectors"][detector]):
            return
        detector_geometry_type = device_dictionary["detectors"][detector][
            MetadataDeviceTags.DETECTOR_GEOMETRY_TYPE.tag]
        detector_position = device_dictionary["detectors"][detector][
            MetadataDeviceTags.DETECTOR_POSITION.tag]
        detector_geometry = np.asarray(
            device_dictionary["detectors"][detector][
                MetadataDeviceTags.DETECTOR_GEOMETRY.tag])

        if detector_geometry_type == "CUBOID":
            if detector_geometry[axes[0]] == 0:
                detector_geometry[axes[0]] = 0.0001
            if detector_geometry[axes[1]] == 0:
                detector_geometry[axes[1]] = 0.0001
            draw_axis.add_patch(
                Rectangle((detector_position[axes[0]] -
                           detector_geometry[axes[0]] / 2,
                           detector_position[axes[1]] -
                           detector_geometry[axes[1]] / 2),
                          detector_geometry[axes[0]],
                          detector_geometry[axes[1]],
                          color="blue"))
        elif detector_geometry_type == "SHPERE" or detector_geometry_type == "CIRCLE":
            draw_axis.add_patch(
                Circle(
                    (detector_position[axes[0]], detector_position[axes[1]]),
                    detector_geometry,
                    color="blue"))
        else:
            print(
                "UNSUPPORTED GEOMETRY TYPE FOR VISUALISATION. WILL DEFAULT TO 'x' visualisation."
            )
            draw_axis.plot(detector_position[axes[0]],
                           detector_position[axes[1]],
                           "x",
                           color="blue")

    for illuminator in device_dictionary["illuminators"]:
        if not (MetadataDeviceTags.ILLUMINATOR_POSITION.tag
                in device_dictionary["illuminators"][illuminator]
                and MetadataDeviceTags.ILLUMINATOR_GEOMETRY.tag
                in device_dictionary["illuminators"][illuminator]):
            return
        illuminator_position = device_dictionary["illuminators"][illuminator][
            MetadataDeviceTags.ILLUMINATOR_POSITION.tag]
        illuminator_orientation = np.asarray(
            device_dictionary["illuminators"][illuminator][
                MetadataDeviceTags.ILLUMINATOR_ORIENTATION.tag])
        illuminator_divergence = device_dictionary["illuminators"][
            illuminator][MetadataDeviceTags.BEAM_DIVERGENCE_ANGLES.tag]
        illuminator_geometry = np.asarray(
            device_dictionary["illuminators"][illuminator][
                MetadataDeviceTags.ILLUMINATOR_GEOMETRY.tag])
        diameter = np.sqrt(
            np.sum(np.asarray([a**2 for a in illuminator_geometry]))) / 2
        illuminator_geometry_type = device_dictionary["illuminators"][
            illuminator][MetadataDeviceTags.ILLUMINATOR_GEOMETRY_TYPE.tag]

        def rot_mat(angle):
            c, s = np.cos(angle), np.sin(angle)
            return np.array(((c, -s), (s, c)))

        if illuminator_geometry_type == "CUBOID":

            angle = np.arctan2(illuminator_orientation[axes[0]],
                               illuminator_orientation[axes[1]])

            if axes[0] == 0 and axes[1] == 1:
                geometry_vector = np.asarray([
                    illuminator_geometry[axes[1]],
                    illuminator_geometry[axes[0]]
                ])
            else:
                geometry_vector = np.asarray([
                    illuminator_geometry[axes[0]],
                    illuminator_geometry[axes[1]]
                ])
            rotated_vector = np.dot(rot_mat(angle), geometry_vector)

            p1 = [
                illuminator_position[axes[0]] - rotated_vector[0] / 2,
                illuminator_position[axes[1]] - rotated_vector[1] / 2
            ]
            p2 = [
                illuminator_position[axes[0]] + rotated_vector[0] / 2,
                illuminator_position[axes[1]] + rotated_vector[1] / 2
            ]
            p3 = [
                p2[0] + illuminator_orientation[axes[0]] +
                illuminator_divergence,
                p2[1] + illuminator_orientation[axes[1]]
            ]
            p4 = [
                p1[0] + illuminator_orientation[axes[0]] -
                illuminator_divergence,
                p1[1] + illuminator_orientation[axes[1]]
            ]

            polypoints = np.asarray([p1, p2, p3, p4, p1])

            plt.gca().add_patch(
                plt.Polygon(xy=polypoints,
                            fill=True,
                            color="yellow",
                            closed=True,
                            alpha=0.5))
            plt.plot([p1[0], p2[0]], [p1[1], p2[1]], color="red")
            if np.abs(p1[0] - p2[0]) < 1e-5 and np.abs(p1[1] - p2[1]) < 1e-5:
                draw_axis.scatter(p1[0], p1[1], marker="+", color="red")
        else:
            draw_axis.scatter(illuminator_position[axes[0]],
                              illuminator_position[axes[1]],
                              marker="+",
                              color="red")
            x = [
                illuminator_position[axes[0]], illuminator_position[axes[0]] +
                illuminator_orientation[axes[0]] / 25
            ]
            y = [
                illuminator_position[axes[1]], illuminator_position[axes[1]] +
                illuminator_orientation[axes[1]] / 25
            ]
            plt.plot(x, y, color="yellow", alpha=1, linewidth=25, zorder=-10)

    start_indexes = np.asarray(axes) * 2
    end_indexes = start_indexes + 1

    draw_axis.add_patch(
        Rectangle((fov[start_indexes[0]], fov[start_indexes[1]]),
                  -fov[start_indexes[0]] + fov[end_indexes[0]],
                  -fov[start_indexes[1]] + fov[end_indexes[1]],
                  color="green",
                  fill=False,
                  label="Field of View"))
Esempio n. 8
0
    def plot_square_around_site(self, edgelength=10, print_distance = True, color = 'white',
                                print_label = None):
        """
        Parameters
        ----------
        edgelength: in km
        print_label: list
            prints the distance to the edge of the box.
            default: ['left', 'bottom']
        """
        col1 = color
        if isinstance(print_label, type(None)):
            print_label = ['left', 'bottom']
        lat = self.lat
        lon = self.lon
        #     bmap = ...
        point_c = (lat, lon)

        dist = _geopy.distance.distance()  # thats just to get an instance of distance, can change the actual distance later in the destination function

        # calculate distance from center to corner of square
        #     el = 10 # edge length of square
        dist2corner = _np.sqrt(2) * edgelength / 2

        # compass bearings to the corners
        bearings = [(i * 90) - 45 for i in (1, 2, 3, 4)]

        # calculate the coordinates of the corners
        corners = []
        for bear in bearings:
            point = dist.destination(point_c, bear, distance=dist2corner)
            corners.append((point.longitude, point.latitude))

        # convert coordinates to x, y
        corners_pt = [self._bmap(*cco) for cco in corners]

        #######
        # repeat for distance text
        # compass bearings to the corners
        label_bearings = [(i * 90)  for i in (0, 1, 2, 3)]

        # calculate the coordinates of the corners
        label_pos = []
        for bear in label_bearings:
            point = dist.destination(point_c, bear, distance=edgelength/2)
            label_pos.append((point.longitude, point.latitude))

        # convert coordinates to x, y
        label_pos_pt = [self._bmap(*cco) for cco in label_pos]

        # plot it
        square = _plt.Polygon(corners_pt)
        square.set_linestyle('--')
        square.set_edgecolor(col1)
        square.set_facecolor([1, 1, 1, 0])
        a = _plt.gca()
        a.add_artist(square)

        #######
        ## plot the distanced on the edges of the square
        labels = []
        label_kwargs = dict(color = col1,
                            fontsize = 'medium',
                            textcoords = 'offset points',
                            )
        text_dist = 5
        txt = f'{edgelength} km'
        if 'top' in print_label:
            lab = label_pos_pt[0]
            anno = a.annotate(txt, (lab[0], lab[1]),
                        xytext=(0, text_dist),va = 'bottom', ha = 'center', **label_kwargs)
            labels.append(anno)

        if 'bottom' in print_label:
            lab = label_pos_pt[2]
            anno = a.annotate(txt, (lab[0], lab[1]),
                              xytext=(0, - text_dist), va='top', ha='center', **label_kwargs)
            labels.append(anno)

        if 'left' in print_label:
            lab = label_pos_pt[3]
            anno = a.annotate(txt, (lab[0], lab[1]),
                              xytext=(- text_dist, 0), va='center', ha='right',
                              rotation=90,
                              **label_kwargs)
            labels.append(anno)

        if 'right' in print_label:
            lab = label_pos_pt[1]
            anno = a.annotate(txt, (lab[0], lab[1]),
                              xytext=(text_dist, 0), va='center', ha='left',
                              rotation=90,
                              **label_kwargs)
            labels.append(anno)
            # a.text(lab[0], lab[1],
            #        # 'bla',
            #        f'{edgelength} km',
            #        color = col1,
            #        va = 'bottom', ha = 'center',
            #        xytext=(0, 35))

        # for lab in label_pos_pt:
        #     a.text(lab[0], lab[1], 'bla')
        # a.plot(x,y, zorder = 100, marker = 'o')
        return square
Esempio n. 9
0
 def draw_poly_patch(self):
     verts = unit_poly_verts(theta)
     return plt.Polygon(verts, closed=True, edgecolor='k')
Esempio n. 10
0
ax.set_xlim(['1/1/2007' , '1/1/2011'])
ax.set_ylim( [600, 1800])
ax.set_title('Important dates in 2008-2009 financial crisis') 


# In[143]:

#图形的绘制要麻烦一些。matplotlib有一些表示常见图形的对象。这些对象被称为块(patch)。
#其中有些可以在matplotlib.pyplot 中找到(如Rectangle和Circ时,但完整集合位于matplotlib.patches

fig= plt.figure()
ax =fig.add_subplot(1, 1, 1)

rect =plt.Rectangle((0.2,0.75),0.4,0.15,color='k',alpha=0.1)
circ =plt.Circle((0.7,0.2),0.15,color='b',alpha=0.3)
pgon = plt.Polygon([[0.15,0.15],[0.35,0.4],[0.2,0.6]],color='g',alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)


# In[485]:

plt.Rectangle((0.2,0.75),0.4,0.15,color='k',alpha=0.1)
show()