Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a grouped pandas data in plotly

I have a pandas dataframe which looks like this:

    A       B
1   USA     Y
3   USA     Y 
4   USA     N
5   India   Y
8   India   N
12  USA     N
14  USA     Y
19  USA     Y   

I want to make a countplot for this dataframe. That is, the plot will have country names on X-axis and the counts for each category on Y-axis. I know I can do this in seaborn like this:

sns.countplot(x='A', data=df, hue='B')

But this will not be an interactive plot. I want to achieve the same thing in plotly but I am having a hard time figuring it out. Can anyone please help me out?

like image 779
mlRocks Avatar asked Nov 13 '18 14:11

mlRocks


1 Answers

Using plotly 3 you can do something like this:

from plotly import graph_objs as go

fig = go.Figure()
for name, group in df.groupby('B'):
    trace = go.Histogram()
    trace.name = name
    trace.x = group['A']
    fig.add_trace(trace)

you can also change other properties like the colors by setting trace.marker.color attribute.

like image 143
vlizana Avatar answered Nov 15 '22 01:11

vlizana