如何使用python字典中的seaborn绘制简单的绘图?

2024-09-28 01:26:15 发布

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

我有一本这样的字典:

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() argument must be a string, a bytes-like object or a number, not 'dict_values'


Tags: 绘图字典mykeysargumentdictintvalues
3条回答

我做了以下工作:

我首先从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

您的代码中有几个问题:

  1. 您正在尝试将每个值(例如“xx.xx%”)转换为一个数字my_dict.values()将所有值作为dict_values对象返回int(my_dict.values()))表示将所有值的集合转换为单个整数,而不是将每个值转换为整数。当然,前者毫无意义
  2. Python无法将“12.34%”之类的内容解释为整数或浮点。您需要删除百分号,即"float(12.34%"[:-1])
  3. 字典是不排序的。因此,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)

你会得到: enter image description here

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

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

相关问题 更多 >

    热门问题