列表字典中1和0的类别图

时间:2018-10-30 22:51:52

标签: python list dictionary plot

我有一本这样的字典:

dict = {'a': [0,1,0,1,0,0,0,0,0], 'b': [1,1,1,1,1,1,1,1,0], 'c': [1,0,1,0,0,0,0,0,0] ...}

目标:绘制类别条形图,其中x轴为键名,y轴为0和1的比例。

key = dict.keys()
values = dict.values()

我知道使用count()可以得到1和0的数量

values.get('a').count(1)

如何使用列表字典绘制类别图?

2 个答案:

答案 0 :(得分:1)

这个怎么样?它需要pandas库。

import pandas as pd

dict = {'a': [0,1,0,1,0,0,0,0,0], 'b': [1,1,1,1,1,1,1,1,0], 'c': [1,0,1,0,0,0,0,0,0] }

df = pd.DataFrame(dict)

df = [df[col].value_counts().to_frame().T for col in ['a', 'b', 'c']]

df = pd.concat(df)

df.plot(kind='bar', stacked=True, rot=0)

enter image description here

答案 1 :(得分:1)

您可以使用matplotlib

import matplotlib.pyplot as plt


data = {
    'a': [0,1,0,1,0,0,0,0,0],
    'b': [1,1,1,1,1,1,1,1,0],
    'c': [1,0,1,0,0,0,0,0,0]
}

keys = list(data.keys()) # ["a", "b", "c"]

我将使用列表推导来构建带有计数的列表:

count_zero = [data[k].count(0) for k in keys] # [7, 1, 7]
count_ones = [data[k].count(1) for k in keys] # [2, 8, 2]

最后绘制数据:

# Create the bar plot
fig, ax = plt.subplots()
ind = list(range(1, len(data) + 1)) # [1, 2, 3, ...] horizontal location of the bars

bars = plt.bar(ind, count_zero)
bars = plt.bar(ind, count_ones, bottom=count_zero)

ax.set_xticks(ind)
ax.set_xticklabels(keys) # labels: a, b, c
ax.set_ylabel('Counts')
ax.set_title('StackOverflow')

plt.show()

结果:

enter image description here