如何从python字典中绘制带有seaborn的简单图?

我有一本这样的字典:

my_dict = {'Southampton': '33.7%', 'Cherbourg': '55.36%', 'Queenstown': '38.96%'}

我怎样才能有一个带有3条形图的简单图表显示字典中每个键的值?

我试过了:

sns.barplot(x=my_dict.keys(), y = int(my_dict.values()))

但是我得到:

TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是'dict_values'
评论
静止oo
静止oo

您需要将值转换为数字,现在它们是字符串:

import seaborn as sns
my_dict = {'Southampton': '33.7%', 'Cherbourg': '55.36%', 'Queenstown': '38.96%'}
perc =  [float(i[:-1]) for i in my_dict.values()]
sns.barplot(x=list(my_dict.keys()),y=perc)

enter image description here

点赞
评论
zrerum
zrerum

您的代码中有几个问题:

  1. You are trying to convert each value (eg "xx.xx%") into a number. my_dict.values() returns all values as a dict_values object. int(my_dict.values())) means converting the set of all values to a single integer, not converting each of the values to an integer. The former, naturally, makes no sense.
  2. Python can't interpret something like "12.34%" as an integer or a float. You need to remove the percentage sign, ie "float(12.34"[:-1]).
  3. Dictionaries are not ordered. Therefore, my_dict.keys() and my_dict.values() are not guaranteed to return keys and values in the key-value pairs in the same order, for example, the keys you get may be ['Southampton', 'Cherbourg', 'Queenstown'] and the values you get may be "55.36%", "33.7", "38.96%".

解决所有这些问题后:

keys = list(my_dict.keys())
# get values in the same order as keys, and parse percentage values
vals = [float(my_dict[k][:-1]) for k in keys]
sns.barplot(x=keys, y=vals)

You get: enter image description here

点赞
评论
bquos
bquos

我做了以下事情:

I first removed the % sign from the dict.

my_df = pd.DataFrame(my_dict.items())
ax = sns.barplot(x=0, y=1, data=my_df)
ax.set(xlabel = 'Cities', ylabel='%', title='Title')

enter image description here

enter image description here

点赞
评论