Plots: bars side by side

question
plotting

#1

Hi there,

I’m using Plots.jl (with PyPlot as the backend) and trying to plot some bars side by side, as in the following example from matplotlib: http://matplotlib.org/examples/api/barchart_demo.html (figure below)

Looking at the documentation of Plots it seemed to me that the attribute I wanted might be bar_position = :stack, but it didn’t work out :confused: the bars are still overlapping.

Can anyone help with this plot?

Thanks in advance!


#2

#3
mn = [20, 35, 30, 35, 27,25, 32, 34, 20, 25]
sx = repeat(["Men", "Women"], inner = 5)
std = [2, 3, 4, 1, 2, 3, 5, 2, 3, 3]
nam = repeat("G" .* string.(1:5), outer = 2)

using StatPlots
groupedbar(nam, mn, yerr = std, group = sx, ylabel = "Scores", 
        title = "Scores by group and gender")

03


#4

Or, to get something closer to your example, you can modify a little:

groupedbar(nam, mn, yerr = std, group = sx, ylabel = "Scores", 
        title = "Scores by group and gender", bar_width = 0.67, 
        lw = 0, c = [:red :darkkhaki], markerstrokewidth = 1.5,
        framestyle = :box, grid = false, yticks = 0:5:35)

04


#5

Thanks very much @ChrisRackauckas and @mkborregaard. Now with mkborregaard’s examples I can make it the way I wanted

Somehow I missed the StatPlots package :sweat_smile:


#6

Maybe it’s a good idea to include this as an example to the README of StatPlots?

Just from looking at the one provided now on GitHub I wouldn’t be able to get my plot the way I wanted to


#7

You’re welcome to put a strong example together and submit a PR :slight_smile:


#8

The syntax in the StatPlots readme uses matrix inputs - that’s also valid but less common:

men = [20, 35, 30, 35, 27]
women = [25, 32, 34, 20, 25]
std_men = [2, 3, 4, 1, 2]
std_women = [3, 5, 2, 3, 3]

groupedbar(["G1", "G2", "G3", "G4", "G5"], [men women], yerr = [std_men std_women])

#9

There is a tiny example with grouping in groupedbar in the StatPlots README, right below the matrix example, showing how to use the group syntax, but admittedly it’s easy to overlook.

@kaslusimoes : it’s shameless self-advertising, but if you need to do some data preprocessing (for example compute mean and sem or std, or some other type of error across all observation or across some variable) before the plot, you could check out the groupedbar examples from GroupedErrors