Search code examples
pythonmatplotlibtkinterdonut-chart

How to make a donut chart in tkinter using matplotlib Figure


I am trying to build a simple program using tkinter and python 3.6. I am stuck when I try to plot a donut chart in my tkinter window using the matplotlib Figure and canvas.

I know how to make a donut chart using the matplotlib pyplot, using a very simple code I found on: https://python-graph-gallery.com/160-basic-donut-plot/

# library
import matplotlib.pyplot as plt

# create data
size_of_groups=[12,11,3,30]

# Create a pieplot
plt.pie(size_of_groups)
#plt.show()

# add a circle at the center
my_circle=plt.Circle( (0,0), 0.7, color='white')
p=plt.gcf()
p.gca().add_artist(my_circle)

plt.show()

I have read that the plots in tkinter should be made using the matplotlib.figure: Placing plot on Tkinter main window in Python Can someone help me how to adjust the code above to be able to plot it inside a Figure that I can place in tkinter canvas?

So far I have only been able to make the pie plot

fig = plt.figure.Figure(figsize=(5,5))
a = fig.add_subplot(111)
a.pie([20,30,50]) #an example data
a.legend(["20","30","50")

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
window= tk.Tk()
canvas = FigureCanvasTkAgg(fig, master=window)
canvas.get_tk_widget().pack()
canvas.draw()
window.mainloop()

But I am unable to add a circle in the center that would hide that part of the pie. Any ideas on how to do that? Thanks


Solution

  • It is indeed a good idea not to use pyplot at all when creating a tk GUI. This is entirely possible using the respective matplotlib objects directly.

    import matplotlib.figure
    import matplotlib.patches
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import tkinter as tk
    
    fig = matplotlib.figure.Figure(figsize=(5,5))
    ax = fig.add_subplot(111)
    ax.pie([20,30,50]) 
    ax.legend(["20","30","50"])
    
    circle=matplotlib.patches.Circle( (0,0), 0.7, color='white')
    ax.add_artist(circle)
    
    window= tk.Tk()
    canvas = FigureCanvasTkAgg(fig, master=window)
    canvas.get_tk_widget().pack()
    canvas.draw()
    window.mainloop()