从字典中检索条形图的值

2024-03-29 07:00:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个字典,供我的条形图(和其他图形)使用,而不是每次手动输入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 |    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)


Tags: seaborndf1setftforcesnsmetvalley
1条回答
网友
1楼 · 发布于 2024-03-29 07:00:53

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

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

但实际上我会把警察部队的名字添加到数据框中:

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)

相关问题 更多 >