python-2.7 - 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!
解决方案
您需要创建一个轴来绘制数据,否则它将选择当前活动的轴,即其中带有单选按钮的轴。
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()
推荐阅读
- report - 如何在 BIRT 报表设计器中设置行距
- php - 使用 Laravel 对 JSON 字段进行不区分大小写的查询
- windows - 为什么 cygwin 找不到 Windows OpenSSH 目录?
- angular - 角模式验证器停止调用 onblur
- cryptography - 汉明距离常数的来源
- python - ListedColormap 用于在 python 中识别 matplotlib.pyplot.grid 中的网格方块
- vba - 组合框值未设置
- javascript - VueJS(或 Vanilla JS)过滤结果的测试对象,包括二级搜索
- android - 如何设置默认 Chrome 自定义标签不必显示“打开方式”
- java - 用两个转义单个反斜杠 \