Tobias J.
Tobias J.

Reputation: 336

Python matplotlib plot dict with multiple values

I am trying to plot a dict with matplotlib, like this (just much more data):

b = {"A": ['26', '44', '10', '22', '26'], "B": ['39', '24'], 'C': ['22', '23'], 'D': ['21', '12']}

I wanted to make one boxplot / violinplot for each key in the dict, (than adding mean, std. deviation, etc.) like: enter image description here

But posts like: Plotting a dictionary with multiple values per key does not work for me, because my keys are letters (coding for amino acids).

I am feeling like i don't see the elephant in the room.

Upvotes: 1

Views: 3020

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339170

You need to bring the data in the form of a list of lists and make sure the data is numeric and not strings. You can then plot them using the boxplot or violinplot commands.

import matplotlib.pyplot as plt

b = {"A": ['26', '44', '10', '22', '26'], "B": ['39', '24'], 
     'C': ['22', '23'], 'D': ['21', '12']}

index= []
data = []
for i, (key, val) in enumerate(b.iteritems()):
    index.append(key)
    data.append(map(float, val))

fig, (ax, ax2) = plt.subplots(ncols=2)
ax.boxplot(data)
ax.set_xticklabels(index)
ax2.violinplot(data)
ax2.set_xticks(range(1,len(index)+1))
ax2.set_xticklabels(index) 

plt.show()

enter image description here

Upvotes: 3

Related Questions