I have a little issue in my code and I hope someone will have an idea to help me. So, I have created a pie chart and, with RadioButtons, I would like to 'control' the 'explode parameter'. Expected result : we have a pie chart, we have Radiobutton and when we click on a radio button, in the pie chart the 'serie' that matches with the Radiobutton clicked is pulled out (thanks to 'explode') and we can do that as long as we want.
My problem : I have created the Radio Buttons, and when they are clicked, it opens a new window with the expected result but I would like to have the pie chart and the Radiobuttons in the same window.
My code just below :
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
rax = plt.axes([0.05, 0.7, 0.15, 0.15])
radio = RadioButtons(rax, ('0-4 ans', '5-10 ans', '11-13 ans', '14-17 ans'))
def explode_function(label):
labels = '0-4 ans', '5-10 ans', '11-13 ans', '14-17 ans'
sizes = [17.4, 25.7, 18.6, 38.3]
explode = (0, 0, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
fig1, ax = plt.subplots()
if label == '0-4 ans':
explode = (0.15, 0, 0, 0)
elif label == '5-10 ans':
explode = (0, 0.15, 0, 0)
elif label == '11-13 ans':
explode = (0, 0, 0.15, 0)
elif label == '14-17 ans':
explode = (0, 0, 0, 0.15)
ax.pie (sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, colors=['lightblue', 'lightgreen', 'salmon', 'lightgray'])
plt.show()
radio.on_clicked(explode_function)
plt.show()```
Thanks a lot, and good evening
CodePudding user response:
By creating the fig
and ax
inside the explode_function
, a new plot will be generated each time a radio button is clicked. Creating the fig
and ax
beforehand, allows to constantly work with the same plot. As an initialization, explode_function(labels[0])
already shows one variant of the pie chart. fig.canvas.redraw()
forces the updated chart to be drawn.
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
fig = plt.figure()
ax = plt.subplot(1, 1, 1)
rax = plt.axes([0.05, 0.7, 0.15, 0.15])
labels = '0-4 ans', '5-10 ans', '11-13 ans', '14-17 ans'
radio = RadioButtons(rax, labels)
def explode_function(label):
ax.cla()
sizes = [17.4, 25.7, 18.6, 38.3]
explode = [0.15 if label == label_i else 0 for label_i in labels]
ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, colors=['lightblue', 'lightgreen', 'salmon', 'lightgray'])
fig.canvas.draw()
explode_function(labels[0])
radio.on_clicked(explode_function)
plt.show()