【问题标题】:Retrieve Values from a Dictionary for a Bar Chart从条形图的字典中检索值
【发布时间】:2019-09-26 11:30:12
【问题描述】:

我正在尝试创建一个将由我的条形图(和其他图表)使用的字典,而不是每次手动输入 x 轴刻度标签,如图所示:query1.set_xticklabels(['Met Police','Thames Valley','Kent'],fontsize=12)

类似这样的事情(虽然我不确定如何实现它):

dict = {'1': 'Met Police','3': 'Cumbria', '4': 'Lancashire', '43': 'Thames Valley', '46': 'Kent'}

这是我的数据框df1。 Police_force 列中的数字对应不同的基于字符串的值。

+---+--------------+---------+
|   | police_force |    ft   |
+---+--------------+---------+
| 0 |      1       |   129   |
| 1 |      43      |   59    |
| 2 |      46      |   56    |
+---+--------------+---------+

这是我的条形图:


# uses seaborn library to generate graph

import seaborn as sns, pandas as pd
%matplotlib inline 
# to plot the graphs inline on jupyter notebook

# set style and size

sns.set(style='darkgrid',palette='rainbow',rc={'figure.figsize':(8,8)})

# read file

df1 = pd.read_csv("1.csv")

# define parameters for query1

query1 = sns.barplot(x=df1.police_force,y=df1.ft,data=df1)

query1.set_title('Polices forces with the most fatal accidents',fontsize=18)
query1.set_xlabel('Police Force',fontsize=14)
query1.set_ylabel('Fatalities',fontsize=12)
query1.set_xticklabels(['Met Police','Thames Valley','Kent'],fontsize=12)

【问题讨论】:

    标签: python dictionary matplotlib jupyter-notebook bar-chart


    【解决方案1】:

    首先,不要将变量命名为 dict,因为它是 Python 中的关键字。假设您将其命名为 pf_dict,那么您要询问的行将变为:

    query1.set_xticklabels([pf_dict[k] for k in df1.police_force], fontsize=12)

    但我实际上会通过将警察部队名称添加到 DataFrame 来做到这一点:

    pf_dict = {
        '1': 'Met Police',
        '3': 'Cumbria',
        '4': 'Lancashire',
        '43': 'Thames Valley',
        '46': 'Kent'
    }
    df1['police_force_name'] = df1['police_force'].map(pf_dict)
    
    # ...
    
    query1.set_xticklabels(df1['police_force_name'], fontsize=12)
    

    【讨论】:

    • 当我输入并执行该代码时,我的条形图都标有“nan”。
    猜你喜欢
    • 1970-01-01
    • 2020-02-07
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多