【问题标题】:creating a graph of dictionary data?创建字典数据图?
【发布时间】:2020-02-21 08:38:55
【问题描述】:

我真的是 python 新手,只是想进行一些基本练习。我今天开始创建基本函数,并想做一个与 this project here. 类似的项目

我想使用不同的数据集 (a superbowl data set) 来执行与上面链接的项目相同的代码。我想使用相同的代码来计算球队赢得超级碗的次数。我的代码可以正常工作,但现在我对绘制这些数据感到好奇。我对大多数图表都使用 matplotlib.pyplot,但这不起作用,因为我使用的是数据字典。我如何绘制这些数据,也许在一个轴上是团队,在另一个轴上是他们的胜利?代码如下:

 # Import pandas
import pandas as pd

# Import Twitter data as DataFrame: df
df = pd.read_csv("https://raw.githubusercontent.com/veeralakrishna/DataCamp-Portfolio-Project-Solutions--Python/master/TV%2C%20Halftime%20Shows%2C%20and%20the%20Big%20Game/datasets/super_bowls.csv")

# Define count_entries()
def count_winners(df, col_name='team_winner'):
    """Return a dictionary with counts of
    wins as value for each team."""

    # Initialize an empty dictionary: cols_count
    wins_count = {}

    # Extract column from DataFrame: col
    col = df[col_name]

    # Iterate over the column in DataFrame
    for entry in col:

       # If entry is in wins_count, add 1
        if entry in wins_count.keys():
           wins_count[entry] += 1

       # Else add the entry to wins_count, set the value to 1
         else:
           wins_count[entry] = 1

# Return the cols_count dictionary
return wins_count

这将返回我要绘制的字典:

{'Philadelphia Eagles': 1, 'New England Patriots': 5, 'Denver Broncos': 3, 'Seattle Seahawks': 1, 'Baltimore Ravens': 2, 'New York Giants': 4, 'Green Bay Packers': 4, 'New Orleans Saints': 1, 'Pittsburgh Steelers': 6, 'Indianapolis Colts': 1, 'Tampa Bay Buccaneers': 1, 'St. Louis Rams': 1, 'Dallas Cowboys': 5, 'San Francisco 49ers': 5, 'Washington Redskins': 3, 'Chicago Bears': 1, 'Los Angeles Raiders': 1, 'Oakland Raiders': 2, 'Miami Dolphins': 2, 'Baltimore Colts': 1, 'Kansas City Chiefs': 1, 'New York Jets': 1}

任何建议将不胜感激!

【问题讨论】:

    标签: python dictionary graph


    【解决方案1】:

    没有理由不能使用 .keys() 和 .values() 绘制字典。这是一个显示水平条形图的示例(我选择了这个方向,因此团队名称在 Y 轴上是可读的)。它基于 Pythonspot.com 上的简单 horizontal barchart example

    import matplotlib.pyplot as plt
    import numpy as np
    
    def plot_wins(data):
        teams = data.keys()
        wins = data.values()
        y_pos = np.arange(len(teams))
    
        plt.barh(y_pos, wins, align='center', alpha=0.5)
        plt.yticks(y_pos, teams)
        plt.xlabel('Wins')
        plt.title('Superbowl Wins by Team')
        plt.tight_layout()
        plt.show()
    
    plot_wins({ 'Philadelphia Eagles': 1, 'New England Patriots': 5, ..etc..})
    

    【讨论】:

    • 谢谢!这是我想要的非常好的可视化。
    【解决方案2】:

    就像您提到的那样,使用 matplotlib 是解决此问题的最佳方法。

    Dict 包含键、值,因此您只需要一种遍历所有键并将其用作 x 值并将 dict 值用作 y 值的方法。 Python 有很多内置模块可以帮助解决这个问题。

    zip - 将元素压缩到tuples 中,这样每个键、值就变成例如(“新英格兰爱国者队”,5)

    import matplotlib.pylab as plt
    
    d = {'Philadelphia Eagles': 1, 'New England Patriots': 5, 'Denver Broncos': 3, 'Seattle Seahawks': 1, 'Baltimore Ravens': 2, 'New York Giants': 4, 'Green Bay Packers': 4, 'New Orleans Saints': 1, 'Pittsburgh Steelers': 6, 'Indianapolis Colts': 1, 'Tampa Bay Buccaneers': 1, 'St. Louis Rams': 1, 'Dallas Cowboys': 5, 'San Francisco 49ers': 5, 'Washington Redskins': 3, 'Chicago Bears': 1, 'Los Angeles Raiders': 1, 'Oakland Raiders': 2, 'Miami Dolphins': 2, 'Baltimore Colts': 1, 'Kansas City Chiefs': 1, 'New York Jets': 1}
    
    
    lists = sorted(d.items()) # sorted by key, return a list of tuples
    #You can sort by values using the following, so the graph would look with increaseing gradient
    # lists = sorted(d.items(), key=lambda kv: kv[1], reverse=True)
    x, y = zip(*lists) # unpack a list of pairs into two tuples
    plt.xlabel('Teams')
    plt.ylabel('Wins')
    plt.plot(x, y)
    plt.xticks(x,rotation='vertical')
    plt.show()
    

    这是上面代码生成的图表。您可能希望缩短键的值以使其看起来更好。

    【讨论】:

    • 谢谢!这就是我要找的东西!
    猜你喜欢
    • 2016-01-14
    • 2020-06-11
    • 2021-12-30
    • 1970-01-01
    • 2023-01-12
    • 2019-10-05
    • 2016-04-15
    • 1970-01-01
    相关资源
    最近更新 更多