Esempio n. 1
0
def test_patch_str():
    """
    Check that patches have nice and working `str` representation.

    Note that the logic is that `__str__` is defined such that:
    str(eval(str(p))) == str(p)
    """
    p = mpatches.Circle(xy=(1, 2), radius=3)
    assert str(p) == 'Circle(xy=(1, 2), radius=3)'

    p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)
    assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'

    p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)
    expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'
    assert str(p) == expected

    p = mpatches.Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2)
    expected = "Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2)"
    assert str(p) == expected

    p = mpatches.RegularPolygon((1, 2), 20, radius=5)
    assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)"

    p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20)
    assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)"

    p = mpatches.FancyBboxPatch((1, 2), width=3, height=4)
    assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)"

    # Further nice __str__ which cannot be `eval`uated:
    path = mpath.Path([(1, 2), (2, 2), (1, 2)], closed=True)
    p = mpatches.PathPatch(path)
    assert str(p) == "PathPatch3((1, 2) ...)"

    p = mpatches.Polygon(np.empty((0, 2)))
    assert str(p) == "Polygon0()"

    data = [[1, 2], [2, 2], [1, 2]]
    p = mpatches.Polygon(data)
    assert str(p) == "Polygon3((1, 2) ...)"

    p = mpatches.FancyArrowPatch(path=path)
    assert str(p)[:27] == "FancyArrowPatch(Path(array("

    p = mpatches.FancyArrowPatch((1, 2), (3, 4))
    assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))"

    p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data')
    assert str(p) == "ConnectionPatch((1, 2), (3, 4))"

    s = mpatches.Shadow(p, 1, 1)
    assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"
Esempio n. 2
0
def test_patch_str():
    """
    Check that patches have nice and working `str` representation.

    Note that the logic is that `__str__` is defined such that:
    str(eval(str(p))) == str(p)
    """
    p = mpatches.Circle(xy=(1, 2), radius=3)
    assert str(p) == 'Circle(xy=(1, 2), radius=3)'

    p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)
    assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'

    p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)
    expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'
    assert str(p) == expected

    p = mpatches.RegularPolygon((1, 2), 20, radius=5)
    assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)"

    p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20)
    assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)"

    p = mpatches.FancyBboxPatch((1, 2), width=3, height=4)
    assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)"

    # Further nice __str__ which cannot be `eval`uated:
    path_data = [([1, 2], mpath.Path.MOVETO), ([2, 2], mpath.Path.LINETO),
                 ([1, 2], mpath.Path.CLOSEPOLY)]
    p = mpatches.PathPatch(mpath.Path(*zip(*path_data)))
    assert str(p) == "PathPatch3((1, 2) ...)"

    data = [[1, 2], [2, 2], [1, 2]]
    p = mpatches.Polygon(data)
    assert str(p) == "Polygon3((1, 2) ...)"

    p = mpatches.FancyArrowPatch(path=mpath.Path(*zip(*path_data)))
    assert str(p)[:27] == "FancyArrowPatch(Path(array("

    p = mpatches.FancyArrowPatch((1, 2), (3, 4))
    assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))"

    p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data')
    assert str(p) == "ConnectionPatch((1, 2), (3, 4))"

    s = mpatches.Shadow(p, 1, 1)
    assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"

    with pytest.warns(MatplotlibDeprecationWarning):
        p = mpatches.YAArrow(plt.gcf(), (1, 0), (2, 1), width=0.1)
        assert str(p) == "YAArrow()"
Esempio n. 3
0
    def _draw_3D_lattice(self, a=2.0, pbc=True):
        all_links = []
        for z in range(self.L[2]):
            for y in range(self.L[1]):
                for x in range(self.L[0]):
                    links = self._get_drawing_links([x * a, y * a, z * a], a)
                    for l in links:
                        all_links.append([[x * a, l[0]], [y * a, l[1]],
                                          [z * a, l[2]]])
                        if (len(all_links) - 1) == 100:
                            self.ax.plot(*all_links[-1], color='red')
                        else:
                            # self.ax.plot(*all_links[-1],
                            #         color='black',
                            #         # color='#a3a2a2',
                            #         lw=1.5,
                            #         zorder=10-a*y
                            # )

                            xx, yy = zip(*all_links[-1])
                            xx = np.array(xx)
                            yy = np.array(yy)

                            ind = {'x': 0, 'y': 1, 'z': 2}
                            for c, d in [[[0, 1], 'z'], [[0, 2], 'y'],
                                         [[1, 2], 'x']]:
                                con = mpatches.ConnectionPatch(
                                    xyA=xx[c],
                                    coordsA=self.ax.transData,
                                    xyB=yy[c],
                                    color='#555555')
                                con.set_linewidth(2.5)
                                shadow = mpatches.Shadow(con,
                                                         1,
                                                         -1,
                                                         props=dict(
                                                             fc="black",
                                                             ec="0.7",
                                                             lw=1,
                                                             capstyle='round'))
                                self.ax.add_patch(con)
                                self.ax.add_patch(shadow)
                                art3d.pathpatch_2d_to_3d(shadow,
                                                         z=xx[ind[d]],
                                                         zdir=d)
                                art3d.pathpatch_2d_to_3d(con,
                                                         z=xx[ind[d]],
                                                         zdir=d)

        return all_links
Esempio n. 4
0
def test_shadow(fig_test, fig_ref):
    xy = np.array([.2, .3])
    dxy = np.array([.1, .2])
    # We need to work around the nonsensical (dpi-dependent) interpretation of
    # offsets by the Shadow class...
    plt.rcParams["savefig.dpi"] = "figure"
    # Test image.
    a1 = fig_test.subplots()
    rect = mpatches.Rectangle(xy=xy, width=.5, height=.5)
    shadow = mpatches.Shadow(rect, ox=dxy[0], oy=dxy[1])
    a1.add_patch(rect)
    a1.add_patch(shadow)
    # Reference image.
    a2 = fig_ref.subplots()
    rect = mpatches.Rectangle(xy=xy, width=.5, height=.5)
    shadow = mpatches.Rectangle(
        xy=xy + fig_ref.dpi / 72 * dxy, width=.5, height=.5,
        fc=np.asarray(mcolors.to_rgb(rect.get_facecolor())) * .3,
        ec=np.asarray(mcolors.to_rgb(rect.get_facecolor())) * .3,
        alpha=.5)
    a2.add_patch(shadow)
    a2.add_patch(rect)
    ax = plt.subplot(212)

    arr = np.arange(256).reshape(1, 256) / 256.

    if usetex:
        s = r"$\displaystyle\left[\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}\right]$!"
    else:
        s = r"$\left[\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}\right]$!"
    text_path = TextPath((0, 0), s, size=40, usetex=usetex)
    text_patch = PathClippedImagePatch(text_path,
                                       arr,
                                       ec="none",
                                       transform=IdentityTransform())

    shadow1 = mpatches.Shadow(text_patch,
                              1,
                              -1,
                              props=dict(fc="none", ec="0.6", lw=3))
    shadow2 = mpatches.Shadow(text_patch,
                              1,
                              -1,
                              props=dict(fc="0.3", ec="none"))

    # make offset box
    offsetbox = AuxTransformBox(IdentityTransform())
    offsetbox.add_artist(shadow1)
    offsetbox.add_artist(shadow2)
    offsetbox.add_artist(text_patch)

    # place the anchored offset box using AnnotationBbox
    ab = AnnotationBbox(
        offsetbox,
Esempio n. 6
0
def fig_powerplants():
    """
    Figure compares the results of the reegis 'get_powerplants_by_region' with
    statistical data of the Federal Network Agency (BNetzA).
    """
    plt.rcParams.update({"font.size": 14})
    geo = geometries.get_federal_states_polygon()

    my_name = "my_federal_states"  # doctest: +SKIP
    my_year = 2015  # doctest: +SKIP
    pp_reegis = powerplants.get_powerplants_by_region(geo, my_year, my_name)

    data_path = os.path.join(
        os.path.dirname(__file__), os.pardir, "data", "static"
    )

    fn_bnetza = os.path.join(data_path, "powerplants_bnetza_2015.csv")
    pp_bnetza = pd.read_csv(fn_bnetza, index_col=[0], skiprows=2, header=[0])

    ax = plt.figure(figsize=(9, 5)).add_subplot(1, 1, 1)

    see = "other renew."

    my_dict = {
        "Bioenergy": see,
        "Geothermal": see,
        "Hard coal": "coal",
        "Hydro": see,
        "Lignite": "coal",
        "Natural gas": "natural gas",
        "Nuclear": "nuclear",
        "Oil": "other fossil",
        "Other fossil fuels": "other fossil",
        "Other fuels": "other fossil",
        "Solar": "solar power",
        "Waste": "other fossil",
        "Wind": "wind power",
        "unknown from conventional": "other fossil",
    }

    my_dict2 = {
        "Biomasse": see,
        "Braunkohle": "coal",
        "Erdgas": "natural gas",
        "Kernenergie": "nuclear",
        "Laufwasser": see,
        "Solar": "solar power",
        "Sonstige (ne)": "other fossil",
        "Steinkohle": "coal",
        "Wind": "wind power",
        "Sonstige (ee)": see,
        "Öl": "other fossil",
    }

    my_colors = [
        "#6c3012",
        "#555555",
        "#db0b0b",
        "#501209",
        "#163e16",
        "#ffde32",
        "#335a8a",
    ]

    pp_reegis = (
        pp_reegis.capacity_2015.unstack().groupby(my_dict, axis=1).sum()
    )

    pp_reegis.loc["EEZ"] = (
        pp_reegis.loc["N0"] + pp_reegis.loc["N1"] + pp_reegis.loc["O0"]
    )

    pp_reegis.drop(["N0", "N1", "O0", "unknown", "P0"], inplace=True)

    pp_bnetza = pp_bnetza.groupby(my_dict2, axis=1).sum()

    ax = (
        pp_reegis.sort_index()
        .sort_index(1)
        .div(1000)
        .plot(
            kind="bar",
            stacked=True,
            position=1.1,
            width=0.3,
            legend=False,
            color=my_colors,
            ax=ax,
        )
    )
    pp_bnetza.sort_index().sort_index(1).div(1000).plot(
        kind="bar",
        stacked=True,
        position=-0.1,
        width=0.3,
        ax=ax,
        color=my_colors,
        alpha=0.9,
    )
    plt.xlabel("federal state / exclusive economic zone (EEZ)")
    plt.ylabel("installed capacity [GW]")
    plt.xlim(left=-0.5)
    plt.subplots_adjust(bottom=0.17, top=0.98, left=0.08, right=0.96)

    b_sum = pp_bnetza.sum() / 1000
    b_total = int(round(b_sum.sum()))
    b_ee_sum = int(round(b_sum.loc[["wind power", "solar power", see]].sum()))
    b_fs_sum = int(
        round(
            b_sum.loc[["natural gas", "coal", "nuclear", "other fossil"]].sum()
        )
    )
    r_sum = pp_reegis.sum() / 1000
    r_total = int(round(r_sum.sum()))
    r_ee_sum = int(round(r_sum.loc[["wind power", "solar power", see]].sum()))
    r_fs_sum = int(
        round(
            r_sum.loc[["natural gas", "coal", "nuclear", "other fossil"]].sum()
        )
    )

    text = {
        "reegis": (2.3, 42, "reegis"),
        "BNetzA": (3.9, 42, "BNetzA"),
        "b_sum1": (0, 39, "total"),
        "b_sum2": (2.5, 39, "{0}       {1}".format(r_total, b_total)),
        "b_fs": (0, 36, "fossil"),
        "b_fs2": (2.5, 36, " {0}         {1}".format(r_fs_sum, b_fs_sum)),
        "b_ee": (0, 33, "renewable"),
        "b_ee2": (2.5, 33, " {0}         {1}".format(r_ee_sum, b_ee_sum)),
    }

    for t, c in text.items():
        plt.text(c[0], c[1], c[2], size=14, ha="left", va="center")

    b = patches.Rectangle((-0.2, 31.8), 5.7, 12, color="#cccccc")
    ax.add_patch(b)
    ax.add_patch(patches.Shadow(b, -0.05, -0.2))
    plt.title("Capacity of power plants in 2014")
    plt.subplots_adjust(right=0.96, left=0.08, bottom=0.17, top=0.93)
    return "compare_power_plants_reegis_bnetza"