matplotlib plot labels&plt.tight不工作,如何修复此代码?

2024-06-26 01:32:23 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我已经生成了绘图,但无法正确拟合,函数使用外部库,我不确定如何修复此问题

 #My code      
opponents = [s() for s in axl.demo_strategies]
    for i, player in enumerate(g_players):
        tf = axl.TransitiveFingerprint(player, opponents=opponents)
        data = tf.fingerprint(turns=20, repetitions=10)
        ...  # Write data to disk for analysis
        plt = tf.plot(display_names=True)
        plt.savefig(f"plot_{i}.png")  # Saves a plot for each player of interest
        plt.show()

外部库为绘图生成这段代码

 def plot(
    self,
    cmap: str = "viridis",
    interpolation: str = "none",
    title: str = None,
    colorbar: bool = True,
    labels: bool = True,
    display_names: bool = False,
    ax: plt.Figure = None,
) -> plt.Figure:
    """Plot the results of the spatial tournament.
    Parameters
    ----------
    cmap : str, optional
        A matplotlib colour map, full list can be found at
        http://matplotlib.org/examples/color/colormaps_reference.html
    interpolation : str, optional
        A matplotlib interpolation, full list can be found at
        http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
    title : str, optional
        A title for the plot
    colorbar : bool, optional
        Choose whether the colorbar should be included or not
    labels : bool, optional
        Choose whether the axis labels and ticks should be included
    display_names : bool, optional
        Choose whether to display the names of the strategies
    ax: matplotlib axis
        Allows the plot to be written to a given matplotlib axis.
        Default is None.
    Returns
    ----------
    figure : matplotlib figure
        A heat plot of the results of the spatial tournament
    """
    if ax is None:
        fig, ax = plt.subplots()
    else:
        ax = ax

    fig = ax.get_figure()
    mat = ax.imshow(self.data, cmap=cmap, interpolation=interpolation)

    width = len(self.data) / 2
    height = width
    fig.set_size_inches(width, height)

    plt.xlabel("turns")
    ax.tick_params(axis="both", which="both", length=0)

    if display_names:
        plt.yticks(
            range(len(self.opponents)), [str(player) for player in self.opponents]
        )
    else:
        plt.yticks([0, len(self.opponents) - 1], [0, 1])
        plt.ylabel("Probability of cooperation")

    if not labels:
        plt.axis("off")

    if title is not None:
        plt.title(title)

    if colorbar:
        max_score = 0
        min_score = 1
        ticks = [min_score, 1 / 2, max_score]

        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.2)
        cbar = fig.colorbar(mat, cax=cax, ticks=ticks)

    plt.tight_layout()
    return fig

我已尝试改变体型大小&;尝试了其他解决方案,但是否有matplotlib向导可以提供帮助

绘图输出 output of plot


Tags: oftheselfforplottitlematplotlibplt