繁体   English   中英

如何填充在条形图顶部绘制的矩形(Tkinter Python)

[英]How to fill a rectangle drawn on top of a bar chart (Tkinter Python)

我正在Python中使用Tkinter构建GUI。 我需要在条形图的顶部绘制一个矩形,并用透明颜色填充该空间。 我已经达到将矩形添加到条形图的地步,但是努力用颜色填充矩形空间。 以下是样本数据文件:

数据文件(dummy.csv):

Val X   Y
4.386535946 4.386535946 2.362683533
3.230578487 3.230578487 1.927068162
2.67663787  2.67663787  1.300859395
2.236096646 2.236096646 1.477402735
1.963946814 1.963946814 1.498125697
1.779245978 1.779245978 0.199055215
-1.38320155 1.159057936 1.38320155
-1.417788412    0.605276953 1.417788412
-1.471051567    1.013028135 1.471051567
-1.477383756    0.996565505 1.477383756
-1.601125344    0.963508674 1.601125344
-3.145657478    0.5902837   3.145657478
-3.241919109    2.796858598 3.241919109

我在下面发布代码。 如果您能帮助我解决难题,我将不胜感激

import tkinter as tk
import pandas as pd

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

class BarGUI(tk.Frame):
    def __init__(self, parent_container):
        tk.Frame.__init__(self, parent_container)        

        self.parent_container = parent_container

        self.fig = Figure(figsize=(7, 3))
        self.a = self.fig.add_subplot(111)

        self.canvas = FigureCanvasTkAgg(self.fig, master=self.parent_container)
        self.canvas.get_tk_widget().grid(column = 0, row = 0, padx = 40, pady = 0)

        tk.Button(self.parent_container, text = "Draw", width = 10, command = self.plot).grid(column = 0, row = 1)


    def read_inputs(self):
        df = pd.read_csv('dummy.csv')
        data = list(df.loc[:, 'Val'])
        data.sort(reverse = True)
        ind = np.arange(len(data))  # the x locations for the groups
        width = 0.95
        return (ind, data, width)


    def plot(self):
        self.a.cla()

        ind, data, width = self.read_inputs()
        self.a.bar(ind, data, width)

        self.a.plot([-1, 13], [1, 1], color = 'orange')
        self.a.plot([13, 13], [1, -1], color = 'orange')
        self.a.plot([13, -1], [-1, -1], color = 'orange')
        self.a.plot([-1, -1], [-1, 1], color = 'orange')

        self.a.set_title ("Scatter Plot", fontsize=16)
        self.a.set_ylabel("Y", fontsize=14)
        self.a.set_xlabel("X", fontsize=14)

        self.canvas.draw()        


root = tk.Tk()
app_window = BarGUI(root)            
root.mainloop()

您可以使用矩形补丁来代替绘制线条来绘制矩形:

    rect = Rectangle((-1, -1), 14, 2, color='orange', fill=True, alpha=0.5)
    self.a.add_artist(rect)

代替

    self.a.plot([-1, 13], [1, 1], color = 'orange')
    self.a.plot([13, 13], [1, -1], color = 'orange')
    self.a.plot([13, -1], [-1, -1], color = 'orange')
    self.a.plot([-1, -1], [-1, 1], color = 'orange')

plot()方法中。 您将需要from matplotlib.patches import Rectangle添加import语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM