Home > Back-end >  How to plot a dictionary of sets in python?
How to plot a dictionary of sets in python?

Time:07-04

I have a dictionary of sets and I want to plot the histogram for it. How can I do that? i tried turning it into lists but it still gives me errors linked to set

#Plot histogram for the first 10
keys = [key for key in frequency.keys()]
val = [value for value in frequency.values()]
values = list(val)
print(type(keys))
print(type(values))

fig, ax = plt.subplots()
ax.bar(np.arange(len(keys)) - 0.2, [value[0] for value in values],
   width=0.2, color='b', align='center')
ax.bar(np.arange(len(keys))   0.2,
   [value[1] if len(value) == 2 else 0 for value in values],
   width=0.2, color='g', align='center')
ax.set_xticklabels(keys)
ax.set_xticks(np.arange(len(keys)))
plt.show()

it give this error: enter image description here

CodePudding user response:

The error says "'set' object is not subscriptable," which means you're trying to access an element of a set with an index, but a set is not an ordered data structure, so you cannot do that.

The problem lies in this line: val = [value for value in frequency.values()].You said you tried turning it into lists, but what you actually created is a list of sets.

So in line 9: ax.bar(np.arange(len(keys)) - 0.2, [value[0] for value in values], value is a set, so you cannot access its elements with [].

To fix this error, do this: val = [list(value) for value in frequency.values()] -> this way you create a list of lists and then in line 9 you can use value[0]

  • Related