简体   繁体   English

如何使用按钮将排序功能添加到 Matplotlib 栏 plot 和行 plot

[英]How to add sort functionality with a Button to a Matplotlib bar plot and line plot

I am just starting out to experiment with visualization in Python.我刚刚开始在 Python 中尝试可视化。 With the following code, I am trying to add sort functionality to a Matplotlib bar plot which is drawn from a data frame.使用以下代码,我正在尝试将排序功能添加到从数据框中绘制的 Matplotlib 条 plot 。 I would like to add a button on the graph like sort , so that when it's click it would display a new plot in the order from the highest sales figure to lowest sales figure, currently the button can be display yet the sort function cannot be triggered.我想在图表上添加一个类似sortbutton ,这样当它被点击时,它会按照从最高销售数字到最低销售数字的顺序显示一个新的 plot,目前该按钮可以显示但排序 function 无法触发. Any idea or pointer would be appreciated.任何想法或指针将不胜感激。

[Updated attempt] [更新尝试]

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

def sort(data_frame):
    sorted = data_frame.sort_values('Sales')
    return data_frame2

def original():
   
    return data_frame

data_frame.plot.bar(x="Product", y="Sales", rot=70, title="Sales Report");
plot.xlabel('Product')
plot.ylabel('Sales')

axcut = plt.axes([0.9, 0.0, 0.1, 0.075])
bsort = Button(axcut,'Sort')
bsort.on_clicked(sort)
axcut2 = plt.axes([1.0, 0.0, 0.1, 0.075])
binit = Button(axcut2,'Original')
binit.on_clicked(original)
plt.show()

Expected graph output预期图 output

在此处输入图像描述

Integration一体化

import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import seaborn as sns
%matplotlib notebook

class Index(object):
        ind = 0
        global funcs
    
        def next(self, event):
            self.ind += 1
            i = self.ind %(len(funcs))
            x,y,name = funcs[i]() # unpack tuple data
            for r1, r2 in zip(l,y):
                r1.set_height(r2)
            ax.set_xticklabels(x)
            ax.title.set_text(name) # set title of graph
            plt.draw()        

class Show():
        
        def trigger(self):
            number_button = tk.Button(button_frame2, text='Trigger', command= self.sort)
        
    
        def sort(self,df_frame):
    
            fig, ax = plt.subplots()
            plt.subplots_adjust(bottom=0.2)
            
            ######intial dataframe
            df_frame
            ######sorted dataframe
            dfsorted = df_frame.sort_values('Sales')
           
    
            x, y = df_frame['Product'], df_frame['Sales']
            x1, y1 = df_frame['Product'], df_frame['Sales']
            x2, y2 = dfsorted['Product'], dfsorted['Sales']
    
            l = plt.bar(x,y)
            plt.title('Sorted - Class')
            l2 = plt.bar(x2,y1)
            l2.remove()
            
            def plot1():
                x = x1
                y = y1
                name = 'ORginal'
                return (x,y,name)
    
            def plot2():
                x = x2
                y = y2
                name = 'Sorteds'
                return (x,y,name)
            
            funcs = [plot1, plot2]        
            callback = Index()
            button = plt.axes([0.81, 0.05, 0.1, 0.075])
            bnext = Button(button, 'Sort', color='green')
            bnext.on_clicked(callback.next)
    
            plt.show()

I have included two reproducible examples using the famous titanic dataset to a basic comparison of class vs. # of survivors for interactive sorting for both matplotlib bar and plot (ie line) sorting on the x-axis below:我已经包含了两个使用著名的titanic数据集的可重复示例,与class# of survivors数量的基本比较,用于matplotlib barplot的交互式排序(即下面的 x 轴排序):

With bar plots you have to loop through the rectangles using set_height , eg for r1, r2 in zip(l,y): r1.set_height(r2) and for line plots, you use set_ydata , eg l.set_ydata(y) .对于bar ,您必须使用set_height遍历矩形,例如for r1, r2 in zip(l,y): r1.set_height(r2)line图,您使用set_ydata ,例如l.set_ydata(y)

Make sure to use %matplotlib notebook if using a jupyter notebook.如果使用 jupyter notebook,请确保使用%matplotlib notebook notebook。

BAR酒吧

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import seaborn as sns
%matplotlib notebook

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)

df = sns.load_dataset('titanic')
df1 = df.groupby('class', as_index=False)['survived'].sum().sort_values('class')
df2 = df1.sort_values('survived', ascending=False)
x, y = df1['class'], df1['survived']
x1, y1 = df1['class'], df1['survived']
x2, y2 = df2['class'], df2['survived']

l = plt.bar(x,y)
plt.title('Sorted - Class')
l2 = plt.bar(x2,y1)
l2.remove()

class Index(object):
    ind = 0
    global funcs

    def next(self, event):
        self.ind += 1
        i = self.ind %(len(funcs))
        x,y,name = funcs[i]() # unpack tuple data
        for r1, r2 in zip(l,y):
            r1.set_height(r2)
        ax.set_xticklabels(x)
        ax.title.set_text(name) # set title of graph
        plt.draw()


def plot1():
    x = x1
    y = y1
    name = 'Sorted - Class'
    return (x,y,name)


def plot2():
    x = x2
    y = y2
    name = 'Sorted - Highest # Survivors'
    return (x,y,name)


funcs = [plot1, plot2]        
callback = Index()
button = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(button, 'Sort', color='green')
bnext.on_clicked(callback.next)

plt.show()

在此处输入图像描述 在此处输入图像描述

LINE线

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import seaborn as sns
%matplotlib notebook

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)

df = sns.load_dataset('titanic')
df1 = df.groupby('class', as_index=False)['survived'].sum().sort_values('class')
df2 = df1.sort_values('survived', ascending=False)
x, y = df1['class'].to_numpy(), df1['survived'].to_numpy()
x1, y1 = df1['class'].to_numpy(), df1['survived'].to_numpy()
x2, y2 = df2['class'].to_numpy(), df2['survived'].to_numpy()
l, = plt.plot(x,y)
plt.title('Sorted - Class')

class Index(object):
    ind = 0
    global funcs

    def next(self, event):
        self.ind += 1
        i = self.ind %(len(funcs))
        x,y,name = funcs[i]() # unpack tuple data
        l.set_ydata(y) #set y value data
        ax.set_xticklabels(x)
        ax.title.set_text(name) # set title of graph
        plt.draw()


def plot1():
    x = x1
    y = y1
    name = 'Sorted - Class'
    return (x,y,name)


def plot2():
    x = x2
    y = y2
    name = 'Sorted - Highest # Survivors'
    return (x,y,name)


funcs = [plot1, plot2]        
callback = Index()
button = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(button, 'Sort', color='green')
bnext.on_clicked(callback.next)

plt.show()

在此处输入图像描述 在此处输入图像描述

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

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