pythonpandasseaborn

Python Seaborn bar graph from DataFrame of wide measurements


I'm struggling with issue of creating a bar graph showing occurrences of measurements stored in DataFrame.

DataFrame has 3 columns (measurement devices name). In each column there are stored measurements values (they are not related to each other)

myExampleDataFrame

I'm looking the way to show occurrences of each measurement value on graph where bars will be columns (measurement devices name).

Till now I'm able to display occurrences in console (separately for each column)

# initialize list of lists
data2 = [[0.5, 0.5, 0.75], [1, 0.75, 0.75], [0.5, 0.75, 0.75], [0.75, 1, 0.75], [0.75, 1, 0.5] , [0.5, 1.5, 0.5]]

# Create the pandas DataFrame
df2 = pd.DataFrame(data2, columns=['Aw1', 'Aw2', 'Bw1'])

for ind in df2:
    print(df2[ind].value_counts())

Aw1
0.50    3
0.75    2
1.00    1
Name: count, dtype: int64
Aw2
0.75    2
1.00    2
0.50    1
1.50    1
Name: count, dtype: int64
Bw1
0.75    4
0.50    2
Name: count, dtype: int64

I'm also able to draw a chart but only presenting single column

sns.catplot(x=df2['Aw1']
        data=df2, 
        aspect=2, 
        kind='count')

Im looking for graph to display all columns at one graph.

So x line to be : 0.50 0.75 1.00 1.50
and on y to be shown occurences from each column (for every x will be 3 bars)

something like this BarGraphManyCategories


Solution

  • Code

    import seaborn as sns
    tmp = df2.stack().reset_index()
    sns.barplot(tmp, x="level_0", y=0, hue='level_1')
    

    enter image description here

    If you want to modify the x-label and y-label, there are several ways to do so, but the simplest is to rename the columns in the variable tmp.