【问题标题】:Matplotlib plot only showing when function endedMatplotlib 图仅显示函数何时结束
【发布时间】:2020-09-07 10:18:35
【问题描述】:

我有以下代码,我希望用户输入来构建条形图。然而,直到用户退出函数,情节才真正显现出来?

def get_plot():
    while True:
        again = input("Do you want to visualise a player's pb scores?")
        if again == 'yes':          
            while True:
                player_name = input("What player do you want to visualise PB scores for the 19/20 season?").title() 
                if player_name in historics.values:
                    print("Player is present within the underlying data")
                    break
                else:
                    print("Player does not exist within the underlying data")

            is_player = historics['Player Name'] == player_name
            new_table = historics[is_player]

            #now we will use this data to produce a bar chart for this player, showing their pb scores over the 19/20 season
            def get_graph():
                plt.bar(new_table.Date,new_table['Matchday Score'],color="g")
                plt.title("%s's PB scores for 19/20 season" % player_name)
                plt.xlabel("Date")
                plt.ylabel("Matchday Score")
                if 'Forward' in new_table['FI Player Current Position'].values:
                    plt.axhline(y=255.56, color='gold', linestyle='-')
                    plt.axhline(y=239.94, color='slategrey', linestyle='-')
                    plt.axhline(y=173.52, color='saddlebrown', linestyle='-')
                elif 'Midfielder' in new_table['FI Player Current Position'].values:
                    plt.axhline(y=262.44, color='gold', linestyle='-')
                    plt.axhline(y=263.35, color='slategrey', linestyle='-')
                    plt.axhline(y=205.66, color='saddlebrown', linestyle='-')
                else:
                    plt.axhline(y=232.62, color='gold', linestyle='-')
                    plt.axhline(y=227.43, color='slategrey', linestyle='-')
                    plt.axhline(y=182.36, color='saddlebrown', linestyle='-')
                plt.rcParams["figure.figsize"]=10,5
                plt.show()
            get_graph()
        if again == 'no':
            break
        else:
            print("Please provide a valid value")
    
get_plot()

所以在输入“no”后,显示最后提供的 player_name 值的图。但是,我希望在输入 player_name 值时创建(并显示)绘图,并在提供的每个后续值时刷新绘图?

我哪里错了?

谢谢。

编辑:数据示例(historics.head()):

        Date       Player Name       Team Name           Opposition  \
0 2020-08-23    Kingsley Coman  Bayern München  Paris Saint Germain   
1 2020-08-23    Joshua Kimmich  Bayern München  Paris Saint Germain   
2 2020-08-23  Thiago Alcántara  Bayern München  Paris Saint Germain   
3 2020-08-23      Manuel Neuer  Bayern München  Paris Saint Germain   
4 2020-08-23       David Alaba  Bayern München  Paris Saint Germain   

  Home or Away?       Competition Starting Lineup? Formation  \
0          Away  Champions League           Lineup   4-2-3-1   
1          Away  Champions League           Lineup   4-2-3-1   
2          Away  Champions League           Lineup   4-2-3-1   
3          Away  Champions League           Lineup   4-2-3-1   
4          Away  Champions League           Lineup   4-2-3-1   

   Matchday Dividends FI Game Position  ... Interceptions Blocks  Clearances  \
0                0.18          Forward  ...           0.0    0.0         0.0   
1                0.10       Midfielder  ...           1.0    1.0         1.0   
2                0.00       Midfielder  ...           2.0    0.0         0.0   
3                0.00       Goalkeeper  ...           0.0    0.0         0.0   
4                0.00         Defender  ...           1.0    0.0         2.0   

   Offsides  Fouls Committed  Yellow Cards  Red Card (Two Yellows)  \
0       0.0              0.0           0.0                     0.0   
1       0.0              1.0           0.0                     0.0   
2       NaN              4.0           0.0                     0.0   
3       0.0              0.0           0.0                     0.0   
4       0.0              0.0           0.0                     0.0   

   Straight Red Cards  Goals Conceded (GKs)  \
0                 0.0                   0.0   
1                 0.0                   0.0   
2                 0.0                   0.0   
3                 0.0                   0.0   
4                 0.0                   0.0   

   Different Game Position to Current FI Position?  
0                                                1  
1                                                1  
2                                                0  
3                                                0  
4                                                0  

【问题讨论】:

  • 您能发布您的数据吗?
  • 在我的初始帖子中添加了一些示例数据

标签: python python-3.x matplotlib jupyter-notebook


【解决方案1】:

这个问题有两个因素:

一方面,您将无法在显示绘图后继续执行代码,除非您使用 matplotlib的交互模式,可以通过plt.ion()激活。 请查看this question

另一方面,如果您想根据用户输入更新绘图,您应该首先创建一个绘图,并保存该引用以在每次用户提供新的player_name 时更新该图。 请查看this question, and its accepted answer

我做了一个简单的例子,我用你提供的数据进行了测试:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd


def plot_player_stats(player_name, historics, fig, ax):
    # validate player name
    if player_name not in historics.values:
        print("Sorry! Unknown player!")
        return

    # search player stats
    is_player = historics['Player Name'] == player_name
    player_stats = historics[is_player]

    # draw bar plot
    ax.clear()
    ax.bar(player_stats.Date, player_stats['Matchday Score'], color="g")
    ax.set_title("%s's PB scores for 19/20 season" % player_name)
    ax.set_xlabel("Date")
    ax.set_ylabel("Matchday Score")

    # ... add lines ...
    plt.draw()


def start_main_plot_loop():

    # load data
    historics = pd.read_csv('sample.csv')

    # initialize plot
    fig, ax = plt.subplots()

    # start loop
    while True:
        player_name = input("Please select a player's name (empty to stop): ")
        if not player_name:
            print("Thanks! See ya soon ma mate!")
            break

        plot_player_stats(player_name, historics, fig, ax)


if __name__ == '__main__':
    plt.ion()
    start_main_plot_loop()

在创建子图时保存ax,并在每次需要绘制新条形图时清除它。

编辑

如果你想在 Jupyter Notebook 上运行它,我唯一能做的就是让它工作:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.display import clear_output # <---- import this function


def plot_player_stats(player_name, historics):
    # validate player name
    if player_name not in historics.values:
        print("Sorry! Unknown player!")
        return

    # search player stats
    is_player = historics['Player Name'] == player_name
    player_stats = historics[is_player]

    # draw bar plot
    plt.bar(player_stats.Date, player_stats['Matchday Score'], color="g")
    plt.title("%s's PB scores for 19/20 season" % player_name)
    plt.xlabel("Date")
    plt.ylabel("Matchday Score")

    # ... add lines ...

    clear_output() # <---- this will clear all cell output!
    plt.show()


def start_main_plot_loop():

    # load data
    historics = pd.read_csv('sample.csv')

    # start loop
    while True:
        player_name = input("Please select a player's name (empty to stop): ")
        if not player_name:
            print("Thanks! See ya soon ma mate!")
            break

        plot_player_stats(player_name, historics)

if __name__ == '__main__':
    start_main_plot_loop()

作为副作用,clear_output 函数将清除单元格内的所有打印输出。让我知道这是否有帮助!

【讨论】:

  • 感谢您的建议!不幸的是,当您退出该功能时,它只会产生一个情节(在我的 Jupyter Notebooks 中)。所以仍然没有能力构建情节,看到它,然后清除它并重建它。
  • @JacobStafford 哦,我不知道您使用的是 jupyter notebook,您是否考虑过在每次更新情节时清除单元格输出?是否需要在单元格输出中保留之前选择的玩家名称?
  • @JacobStafford 我使用clear_outputfor Jupyter Notebooks 更新了我的回复
  • 太棒了!很有魅力。非常感谢。
  • 伟大的@JacobStafford,我很高兴它成功了!请记住将答案标记为已接受,以便将来帮助其他用户!
猜你喜欢
  • 2014-04-29
  • 1970-01-01
  • 2018-12-27
  • 2023-01-08
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
相关资源
最近更新 更多