Python matplotlib中绘图外的图例

2024-10-01 11:22:28 发布

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

我试图在matplotlib中的情节之外放置一个相当广泛的传说。传说中有很多条目,每个条目都可能很长(但我不知道具体多长)。在

显然,这很容易使用

legendHandle = plt.legend(loc = "center left", bbox_to_anchor = (1, 0.5))

但问题是这个传说被窗户的边缘切断了。我花了很长时间寻找解决办法。到目前为止,我能找到的最好的东西是:

^{pr2}$

不幸的是,这并不能真正解决我的问题。由于将显式系数0.8应用于方框宽度,因此这仅适用于图形和图例宽度的一个特定组合。如果我调整“体形”窗口的大小,或者图例项的长度不同,则无法正常工作。在

我只是不明白把一个传奇人物放在人物之外是多么困难。我习惯了Matlab,它很简单

legend('Location', 'eastoutside')

在Python中有没有我遗漏的东西?在


Tags: to宽度matplotlib条目pltleftloccenter
3条回答

刚才无意中发现了这个问题,我想你可以用这个数字的图例方法:

import matplotlib.pyplot as plt

# sample data
x1 = [1,2,3,4,5,6]
y1 = [0,1,0,1,0,1]
x2 = [1,2,3,4,5,6]
y2 = [9,8,8,7,8,6]

fig = plt.figure(figsize=(4, 2), dpi=100)
ax = fig.add_subplot(111)

ax.plot(x1,y1,x2,y2)

fig.legend(loc=1, mode='expand', numpoints=1, ncol=4, fancybox = True,
           fontsize='small', labels=['d1', 'd2'])
# loc=1 means at the top-right of the figure

plt.show()

虽然图例位于轴外部,但如果图例太大,它可能仍与轴重叠。在

Pyplot legend outside of axis

图例的放置可以通过使用参数来控制 locbbox_-to-uAnchor。 下面是一个代码示例:

import matplotlib.pyplot as plt

#sample data
import numpy as np
x = np.linspace(0, 2, 101)

#create figure and its axes
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])

#plot 3 lines and define their labels
ax.plot(x, x**2, label="square")
ax.plot(x, x**3, label="cubic")
ax.plot(x, np.sin(x), label="sinus")

#place the legend
ax.legend(loc='lower center', bbox_to_anchor=(0.5, 1.0), ncol=3)
  # The center of the lower edge of the rectangle containing the legend
  # is placed at coordinates (x,y)=(0.5,1.0) of ax. 
  # Thus, figure and legend should not overlap.

plt.show()

现在您应该看到下图: figure with legend outside

经过多次尝试,这是我能想到的最好的:

from matplotlib.lines import Line2D
from matplotlib.gridspec import GridSpec
from enum import Enum

class Location(Enum):
    EastOutside = 1
    WestOutside = 2
    NorthOutside = 3
    SouthOutside = 4

class Legend:
    def __init__(self, figure, plotAxes, location: Location):
        self.figure = figure
        self.plotAxes = plotAxes
        self.location = location

        # Create a separate subplot for the legend. Actual location doesn't matter - will be modified anyway.
        self.legendAxes = figure.add_subplot(1, 2, 1)
        self.legendAxes.clear() # remove old lines
        self.legendAxes.set_axis_off()

        # Add all lines from the plot to the legend subplot
        for line in plotAxes.get_lines():
            legendLine = Line2D([], [])
            legendLine.update_from(line)
            self.legendAxes.add_line(legendLine)

        if self.location == Location.EastOutside:
            self.legend = self.legendAxes.legend(loc = "center left")
        elif self.location == Location.WestOutside:
            self.legend = self.legendAxes.legend(loc = "center right")
        elif self.location == Location.NorthOutside:
            self.legend = self.legendAxes.legend(loc = "lower center")
        elif self.location == Location.SouthOutside:
            self.legend = self.legendAxes.legend(loc = "upper center")
        else:
            raise Exception("Unknown legend location.")

        self.UpdateSize()

        # Recalculate legend size if the size changes
        figure.canvas.mpl_connect('resize_event', lambda event: self.UpdateSize())

    def UpdateSize(self):
        self.figure.canvas.draw() # draw everything once in order to get correct legend size

        # Extract legend size in percentage of the figure width
        legendSize = self.legend.get_window_extent().inverse_transformed(self.figure.transFigure)
        legendWidth = legendSize.width
        legendHeight = legendSize.height

        # Update subplot such that it is only as large as the legend
        if self.location == Location.EastOutside:
            gridspec = GridSpec(1, 2, width_ratios = [1 - legendWidth, legendWidth])
            legendLocation = 1
            plotLocation = 0
        elif self.location == Location.WestOutside:
            gridspec = GridSpec(1, 2, width_ratios = [legendWidth, 1 - legendWidth])
            legendLocation = 0
            plotLocation = 1
        elif self.location == Location.NorthOutside:
            gridspec = GridSpec(2, 1, height_ratios = [legendHeight, 1 - legendHeight])
            legendLocation = 0
            plotLocation = 1
        elif self.location == Location.SouthOutside:
            gridspec = GridSpec(2, 1, height_ratios = [1 - legendHeight, legendHeight])
            legendLocation = 1
            plotLocation = 0
        else:
            raise Exception("Unknown legend location.")

        self.legendAxes.set_position(gridspec[legendLocation].get_position(self.figure))
        self.legendAxes.set_subplotspec(gridspec[legendLocation]) # to make figure.tight_layout() work if that's desired

        self.plotAxes.set_position(gridspec[plotLocation].get_position(self.figure))
        self.plotAxes.set_subplotspec(gridspec[plotLocation]) # to make figure.tight_layout() work if that's desired

在我迄今为止测试过的案例中,这个传说或多或少是好的。用法是

^{pr2}$

让我问一个问题,我已经在一个评论。。。对于matplotlib开发人员,我该如何建议将其作为一个附加特性呢?(不是我的黑客,而是一种在人物之外拥有传奇的本土方式)

相关问题 更多 >