【问题标题】:How to make a donut chart in tkinter using matplotlib Figure如何在 tkinter 中使用 matplotlib 图制作甜甜圈图
【发布时间】:2018-08-12 03:47:29
【问题描述】:

我正在尝试使用 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()

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

【问题讨论】:

    标签: python matplotlib tkinter donut-chart


    【解决方案1】:

    在创建 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()
    

    【讨论】:

    • 谢谢,ax.add_artist(circle) 正是我完成剧情所缺少的
    猜你喜欢
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多