python - 如何使用按钮向 Matplotlib 条形图和折线图添加排序功能

标签 python python-3.x matplotlib seaborn

我刚刚开始尝试用 Python 进行可视化。使用以下代码,我尝试向从数据框绘制的 Matplotlib 条形图添加排序功能。我想在图表上添加一个按钮,例如sort,这样当单击它时,它会按照从最高销售额到最低销售额的顺序显示一个新图,目前可以显示按钮,但无法触发排序功能。任何想法或指示将不胜感激。

[更新的尝试]

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

预期图形输出

enter image description here

集成

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

最佳答案

我提供了两个可重现的示例,使用著名的titanic数据集对class幸存者数量进行基本比较,以进行交互式排序matplotlib barplot (即线)在下面的 x 轴上排序:

使用bar图,您必须使用set_height循环遍历矩形,例如对于 zip(l,y) 中的 r1, r2: r1.set_height(r2) 和对于 line 绘图,您可以使用 set_ydata,例如l.set_ydata(y)

如果使用 jupyter 笔记本,请确保使用 %matplotlib 笔记本

酒吧

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

enter image description here enter image description here

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

enter image description here enter image description here

关于python - 如何使用按钮向 Matplotlib 条形图和折线图添加排序功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65638708/

相关文章:

python - 如何在jupyter笔记本中并排显示图像

python - Pandas 情节中的小刻度线

python - for 循环中函数的子图

python - 使用 python3 将非 ASCII 字符传递给 PyQt4 的 tr() 国际化方法

python - 从 Haskell 到函数式 Python

Python 文本处理 : NLTK and pandas

python - 在 Python 2.7 中,通过 super(self.__class__, self)... 调用 super 构造函数不是更好吗?

python-3.x - 如何在我的 spark 2.4.7 中连接和写入 postgres jdbc?

python - 如何使用网格移动图像?

python - 如何用 numpy/scipy 生成矩形脉冲