Reputation: 1905
I have a dict d
which lists numbers' occurences:
{'item1': [42, 1, 2, 3, 42, 2, 1, 1, 1, 1, 1],
'item2': [2, 5],
'item3': [5, 1, 7, 2, 7, 1, 42, 2, 9]}
Which I then convert to a DataFrame counting these occurences:
df = pd.DataFrame.from_dict({k: dict(Counter(v)) for k, v in d.items()})
item1 item2 item3
42 2.0 NaN 1.0
1 6.0 NaN 2.0
2 2.0 1.0 2.0
3 1.0 NaN NaN
5 NaN 1.0 1.0
7 NaN NaN 2.0
9 NaN NaN 1.0
How can I plot this or some other DataFrame that was derived from d
using seaborn.violinplot
, so that each column in the dataframe represents a violin in the plot based on the data provided by each columns values and their respective indices?
I have tried multiple combinations of which I believe this intuitively comes the closest, but unfortunately still fails:
sns.violinplot(x=df.keys(), y=df.index, data=df)
Upvotes: 1
Views: 415
Reputation: 1883
Code below creates the plot:
# Import libraries
import pandas as pd
import collections
import seaborn as sns
# Create dictionary
d = {'item1': [42, 1, 2, 3, 42, 2, 1, 1, 1, 1, 1],
'item2': [2, 5],
'item3': [5, 1, 7, 2, 7, 1, 42, 2, 9]}
# Create DataFrame and melt
df = pd.DataFrame.from_dict({k: dict(collections.Counter(v)) for k, v in d.items()})
df = df.melt()
# Plot
sns.violinplot(x="variable", y="value", data=df)
Upvotes: 2
Reputation: 40747
Simply this is enough
from collections import Counter
d = {'item1': [42, 1, 2, 3, 42, 2, 1, 1, 1, 1, 1],
'item2': [2, 5],
'item3': [5, 1, 7, 2, 7, 1, 42, 2, 9]}
df = pd.DataFrame.from_dict({k: dict(Counter(v)) for k, v in d.items()})
sns.violinplot(data=df)
Upvotes: 2
Reputation: 863611
Pass DataFrame
to seaborn.violinplot
, so each Series (column) is plotted separately:
sns.violinplot(data=df)
Upvotes: 2