首页 > 解决方案 > changing the plot of a graph based on the items of a dictionary using radiobuttons

问题描述

I have a dictionary containing a number of items. I would like to create single graph with the number of radio buttons equaling the number of items in the dictionary. The radio button options would be the keys of the dictionary, and the associated values would be plotted accordingly every time you selected a different radio button. For example:

from matplotlib.widgets import Slider, Button, RadioButtons

data = {'A' : [1,2,4,6,7,8,10],'B' : [1,2,4,6,4,3,7], 'C' : [3,2,1,6,2,3,4]}

axcolor = 'lightgoldenrodyellow'
rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, data.keys(), active=0)

def chooseGraph(graph):
    [plt.plot(data[names]) for names in data.keys()]
radio.on_clicked(chooseGraph)

plt.show()

When I execute this code, I get the radio buttons, but no graph. When I select a button, all 3 datasets are plotted over the top of the radio button, and changing the buttons just changes the colour.

Thanks for your help in advance!

标签: python-2.7matplotlibradio-buttonnsdictionary

解决方案


您需要创建一个轴来绘制数据,否则它将选择当前活动的轴,即其中带有单选按钮的轴。

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

data = {'A' : [1,2,4,6,7,8,10],'B' : [1,2,4,6,4,3,7], 'C' : [3,2,1,6,2,3,4]}

fig, ax = plt.subplots()
ax.plot(data["A"])

rax = fig.add_axes([0.025, 0.5, 0.15, 0.15])
radio = RadioButtons(rax, sorted(data.keys()), active=0)

def chooseGraph(graph):
    ax.clear()
    ax.plot(data[graph])
    fig.canvas.draw_idle()

radio.on_clicked(chooseGraph)

plt.show()

推荐阅读