如何使用set_radius设置Matplotlib RadioButton半径?

问题描述

我尝试设置RadioButtons的圆半径。根据下面的MWE,按钮消失了。但是,删除circ.set_radius(10)将恢复按钮。使用circ.heightcirc.width会恢复按钮,如果操作正确,它们将是完美的圆形。知道什么原因导致无法使用set_radius吗?

import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons

buttonlist = ('at current position','over width around cur. pos.','at plots full range')

axradio = plt.axes([0.3,0.3,0.2,0.2])
radios = RadioButtons(axradio,buttonlist)

for circ in radios.circles:
    circ.set_radius(10)

plt.show()

只需添加:我在Windows上使用Python 3.6.8(32位版本)。 Matplotlib 3.3.2。

解决方法

一些评论。 如果创建新轴,则x和y的默认限制为(0,1)。 因此,如果创建半径为10的圆,则看不到该圆。 尝试将半径设置为较小的值(即0.1

另一件事是,在大多数情况下,x和y轴的https://github.com/jualston/wingit/blob/master/P2milestone1.html不相等,这意味着圆看起来像椭圆。 您在这里有不同的选择,一种是使用关键字aspect='equal'aspect=1

import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons

buttonlist = ('at current position','over width around cur. pos.','at plots full range')
axradio = plt.axes([0.3,0.3,0.6,0.2],aspect=1)
radios = RadioButtons(axradio,buttonlist)

aspect ratio

另一个选择是使用aspect='auto'答案并获取轴的纵横比。使用此功能,您可以像以前一样调整宽度和高度,但是通过这种方式,您就不必猜测正确的比例了。这种方法的优点是,您在轴的宽度和高度方面更加灵活。

def get_aspect_ratio(ax=None):
    """https://stackoverflow.com/questions/41597177/get-aspect-ratio-of-axes"""
    if ax is None:
        ax = plt.gca()
    fig = ax.get_figure()

    ll,ur = ax.get_position() * fig.get_size_inches()
    width,height = ur - ll
    return height / width

plt.figure()
axradio = plt.axes([0.3,0.2])
radios = RadioButtons(axradio,buttonlist)

r = 0.2
for circ in radios.circles:
    circ.width = r * get_aspect_ratio(axradio)
    circ.height = r

this