亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

即使調整圖形大小,如何獲得圖例和軸之間的恒定距離?

即使調整圖形大小,如何獲得圖例和軸之間的恒定距離?

哈士奇WWW 2021-12-08 14:43:38
當使用bbox_to_anchoras in this answer將圖例放置在軸之外時,軸和圖例之間的空間會在調整圖形大小時發生變化。對于靜態導出的圖,這很好;你可以簡單地調整數字,直到你做對了。但是對于您可能想要調整大小的交互式繪圖,這是一個問題。從這個例子中可以看出:import numpy as npfrom matplotlib import pyplot as pltx = np.arange(5)y = np.random.randn(5)fig, ax = plt.subplots(tight_layout=True)ax.plot(x, y, label='data1')ax.plot(x, y-1, label='data2')legend = ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), ncol=2)plt.show()結果:即使調整圖形大小,如何確保圖例與軸的距離相同?
查看完整描述

2 回答

?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

圖例與邊界框邊緣的距離由borderaxespad參數設置。的borderaxespad是在字體大小的倍數為單位-使它自動獨立的軸尺寸。所以在這種情況下,


import matplotlib.pyplot as plt

import numpy as np

x = np.arange(5)

y = np.random.randn(5)


fig, ax = plt.subplots(constrained_layout=True)

ax.plot(x, y, label='data1')

ax.plot(x, y-1, label='data2')

legend = ax.legend(loc="upper center", bbox_to_anchor=(0.5,0), borderaxespad=2)


plt.show()

http://img1.sycdn.imooc.com//61b054420001823902530162.jpg

http://img1.sycdn.imooc.com//61b0544b0001758f02550057.jpg

在軸圖形底部的地方標題中提出了一個類似的問題,即在軸下方以恒定距離顯示標題


查看完整回答
反對 回復 2021-12-08
?
慕桂英4014372

TA貢獻1871條經驗 獲得超13個贊

您可以使用畫布的調整大小事件來更新bbox_to_anchor每次更新時的值。要計算新值,您可以使用軸變換 ( Bbox.inverse_transformed(ax.transAxes))的逆變換,它將以像素為單位的屏幕坐標轉換為 .x 中通常使用的軸坐標bbox_to_anchor。


這是一個支持將圖例放在軸的所有四個邊上的示例:


import numpy as np

from matplotlib import pyplot as plt

from matplotlib.transforms import Bbox



class FixedOutsideLegend:

    """A legend placed at a fixed offset (in pixels) from the axes."""


    def __init__(self, ax, location, pixel_offset, **kwargs):

        self._pixel_offset = pixel_offset


        self.location = location

        if location == 'right':

            self._loc = 'center left'

        elif location == 'left':

            self._loc = 'center right'

        elif location == 'upper':

            self._loc = 'lower center'

        elif location == 'lower':

            self._loc = 'upper center'

        else:

            raise ValueError('Unknown location: {}'.format(location))


        self.legend = ax.legend(

            loc=self._loc, bbox_to_anchor=self._get_bbox_to_anchor(), **kwargs)

        ax.figure.canvas.mpl_connect('resize_event', self.on_resize)


    def on_resize(self, event):

        self.legend.set_bbox_to_anchor(self._get_bbox_to_anchor())


    def _get_bbox_to_anchor(self):

        """

        Find the lengths in axes units that correspond to the specified

        pixel_offset.

        """

        screen_bbox = Bbox.from_bounds(

            0, 0, self._pixel_offset, self._pixel_offset)

        try:

            ax_bbox = screen_bbox.inverse_transformed(ax.transAxes)

        except np.linagl.LinAlgError:

            ax_width = 0

            ax_height = 0

        else:

            ax_width = ax_bbox.width

            ax_height = ax_bbox.height


        if self.location == 'right':

            return (1 + ax_width, 0.5)

        elif self.location == 'left':

            return (-ax_width, 0.5)

        elif self.location == 'upper':

            return (0.5, 1 + ax_height)

        elif self.location == 'lower':

            return (0.5, -ax_height)



x = np.arange(5)

y = np.random.randn(5)


fig, ax = plt.subplots(tight_layout=True)

ax.plot(x, y, label='data1')

ax.plot(x, y-1, label='data2')

legend = FixedOutsideLegend(ax, 'lower', 20, ncol=2)

plt.show()

結果:

http://img1.sycdn.imooc.com//61b0545e0001ad7e12790476.jpg

查看完整回答
反對 回復 2021-12-08
  • 2 回答
  • 0 關注
  • 260 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號