【问题标题】:How to have separate axes for radio buttons and histogram plot?如何为单选按钮和直方图设置单独的轴?
【发布时间】:2020-05-24 16:01:14
【问题描述】:

当我在这里运行我的代码时:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from matplotlib.widgets import RadioButtons
from matplotlib.widgets import Slider
%matplotlib notebook
# generate 4 random variables from the random, gamma, exponential, and uniform distributions

sample_size = 10000
normal = np.random.normal(loc=0.0, scale=1.0, size=sample_size)
gamma = np.random.gamma(shape = 1.0, scale=1.0, size=sample_size)
uniform = np.random.uniform(low=0.0, high=10.0, size=sample_size)
exponential = np.random.exponential(scale=1.0, size=sample_size)

axcolor = 'lightgoldenrodyellow'
rax = plt.axes([0.05, 0.7, 0.25, 0.25], facecolor=axcolor)

radio = RadioButtons(rax, ('Normal', 'Gamma', 'Uniform', 'Exponential'))

def dist_func(type_l):
    dist_dict = {'Normal':normal, 'Gamma':gamma, 'Uniform':uniform, 'Exponential':exponential}
    data_type = dist_dict[type_l]
    hist = plt.hist(data_type,bins=100, axes=hax)
    plt.draw()

radio.on_clicked(dist_func)

我的直方图显示在使用单选按钮定义的轴内,我希望它显示为正常的直方图,其中 matplotlib 获取轴值。

有什么办法可以做到吗?

【问题讨论】:

  • 你的axes=hax中的hax是什么?
  • 抱歉,我尝试为直方图制作另一个坐标轴>

标签: python matplotlib


【解决方案1】:

您将需要使用 子图 来实现您的目标。否则,单选框和直方图会重叠。

请参考以下内容

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from matplotlib.widgets import RadioButtons
from matplotlib.widgets import Slider

# generate 4 random variables from the random, gamma, exponential, and uniform distributions
sample_size = 10000
normal = np.random.normal(loc=0.0, scale=1.0, size=sample_size)
gamma = np.random.gamma(shape = 1.0, scale=1.0, size=sample_size)
uniform = np.random.uniform(low=0.0, high=10.0, size=sample_size)
exponential = np.random.exponential(scale=1.0, size=sample_size)

fig, sub_plt = plt.subplots()
plt.subplots_adjust(top=0.65) # Adjust subplot to not overlap with radio box

axcolor = 'lightgoldenrodyellow'
rax = plt.axes([0.05, 0.7, 0.25, 0.25], facecolor=axcolor)
radio = RadioButtons(rax, ('Normal', 'Gamma', 'Uniform', 'Exponential'))

def dist_func(type_l):
    sub_plt.clear() # comment this line if you want to keep previous drawings
    dist_dict = {'Normal':normal, 'Gamma':gamma, 'Uniform':uniform, 'Exponential':exponential}
    data_type = dist_dict[type_l]
    hist = sub_plt.hist(data_type,bins=100)
    plt.draw()

radio.on_clicked(dist_func)
plt.show()

【讨论】:

  • 我调整了我的代码以匹配您的代码,但单选按钮似乎不再起作用,有没有办法解决这个问题?
  • 我不确定。上面的代码实际运行并且选择按钮有效。你能分享你调整后的代码吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
相关资源
最近更新 更多