seaborn

How to customize color palette in stacked bar plots created with seaborn.objects.Plot() constructor call?


According to the API documentation of seaborn at pydata, a stacked bar plot has to be plotted like the following:

so.Plot(titanic, x="class", color="sex").add(so.Bar(), so.Count(), so.Stack())

The resulting plot appears like this: stacked bar plot

While this serves my purpose well, but I would need a way to change the color palette that sets the color for the two categories of data (namely, male and female in the example above).

I have went through the documentation for so.Plot() and so.Bars(), but I am at a loss finding anything useful


Solution

  • For more specific way to control color pass the dict.

    titanic = sns.load_dataset("titanic")  # Example dataset
    (
        so.Plot(titanic, x="class", color="sex")
        .add(so.Bar(), so.Count(), so.Stack())
        .scale(color={'male':'green','female':'red'})
    )
    

    enter image description here

    Since the guru(@mwaskom) himself is here can I ask how we can do the same for line width and styles?

    p=so.Plot(fmri, "timepoint", "signal", color="event")
    p.add(so.Line(), so.Agg())
    

    event col has two values "cue" and "stem" I want stem to be solid and width of 1 and color black and cue to be dashed and width of 3 and color red. Unlike I can pass dict for color I can not pass dict for width and style. It would have been nice if there is some consistency but I can understand perhaps color is more general attribute than style and width which are applicable to only a subset like lines etc. I am still learning.

    enter image description here

    Finally after few hours of hit and trial.

    p=so.Plot(fmri, "timepoint", "signal", linewidth="event")
    p=p.add(so.Line(), so.Agg())
    p=p.scale(linewidth={'cue':3,'stim':1})
    

    enter image description here

    And same for style as well.Basically scale takes color, style, width etc if they are defined in other layers.

    Putting it all together.

    p=so.Plot(fmri, "timepoint", "signal", color="event",linestyle="event",linewidth="event")
    p=p.add(so.Line(), so.Agg())
    p=p.scale(color={'cue':'red','stim':'black'},
              linestyle={'cue':'dashed','stim':'solid'},
              linewidth={'cue':3,'stim':1})
    

    enter image description here

    I guess going forward seaborn should focus on object interface more and deprecate the old interface. Object interface seems to be more powerful and is easier for people who are coming from ggplot.