matplotlib 如何从python字典中用seaborn绘制一个简单的图?

mspsb9vt  于 12个月前  发布在  Python
关注(0)|答案(3)|浏览(133)

我有一本这样的字典:

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'

1aaf6o9v

1aaf6o9v1#

您的代码中有几个问题:
1.您试图将每个值(例如“xx.xx%”)转换为数字。my_dict.values()将所有值作为dict_values对象返回。int(my_dict.values()))意味着将所有值的集合转换为单个整数,而不是将每个值转换为整数。前者自然没有意义。

  1. Python不能将“12.34%”解释为整数或浮点数。您需要删除百分比符号,即float("12.34%"[:-1])
    1.字典是没有顺序的。因此,my_dict.keys()my_dict.values()不能保证以相同的顺序返回键值对中的键和值,例如,你得到的键可能是['Southampton', 'Cherbourg', 'Queenstown'],你得到的值可能是"55.36%", "33.7", "38.96%"。这在Python >= 3.7和CPython 3.6中不再是问题;请参阅下面@AmphotericLewisAcid的评论。
    解决了所有这些问题后:
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)

你得到:x1c 0d1x

polkgigr

polkgigr2#

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

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)

wz1wpwve

wz1wpwve3#

我做了以下操作:
首先,我从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')

相关问题