首页 文章

如何使用matplotlib在tkinter中制作圆环图

提问于
浏览
1

我正在尝试使用tkinter和python 3.6构建一个简单的程序 . 当我尝试使用matplotlib图和画布在我的tkinter窗口中绘制圆环图时,我陷入困境 .

我知道如何使用matplotlib pyplot制作圆环图,使用我发现的非常简单的代码: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()

我已经读过tkinter中的图应该使用matplotlib.figure:Placing plot on Tkinter main window in Python有人可以帮助我如何调整上面的代码,以便能够将它绘制在我可以放置在tkinter画布中的图中吗?

到目前为止,我只能制作饼图

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()

但我无法在中心添加一个隐藏那部分馅饼的圆圈 . 有关如何做到这一点的任何想法?谢谢

1 回答

  • 0

    在创建tk GUI时,根本不使用 pyplot 确实是一个好主意 . 这完全可以直接使用相应的matplotlib对象 .

    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()
    

相关问题