Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: group x axis discrete values into subgroups

I would like to create a bar plot with ggplot2 in which the discrete values of the x axis would be grouped into subgroups (see picture attached - the picture is from the web I do not have a code for the plot yet).

enter image description here

Thanks for your help !

like image 913
lqdo2000 Avatar asked Apr 21 '14 23:04

lqdo2000


People also ask

How do I change the X axis scale in ggplot2?

Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.

How do you specify axes in ggplot2?

Setting the axis bounds on a plot using ggplot2 is a common task. Using the following functions, you can accomplish so quickly. xlim(): specifies the lower and upper limit of the x-axis. ylim(): specifies the lower and upper limit of the y-axis.

What does XLAB mean in R?

xlab="x-axis label", ylab="y-axis label") Many other graphical parameters (such as text size, font, rotation, and color) can also be specified in the title( ) function.

What is AES group?

January 2022) The AES Corporation is an American utility and power generation company. It owns and operates power plants, which it uses to generate and sell electricity to end users and intermediaries like utilities and industrial facilities.


1 Answers

Two approaches:

Example data:

dat <- data.frame(value=runif(26)*10,
                  grouping=c(rep("Group 1",10),
                             rep("Group 2",10),
                             rep("Group 3",6)),
                  letters=LETTERS[1:26])

head(dat)
     value grouping letters
1 8.316451  Group 1       A
2 9.768578  Group 1       B
3 4.896294  Group 1       C
4 2.004545  Group 1       D
5 4.905058  Group 1       E
6 8.997713  Group 1       F

Without facetting:

ggplot(dat, aes(grouping, value, fill=letters, label = letters)) + 
     geom_bar(position="dodge", stat="identity") + 
     geom_text(position = position_dodge(width = 1), aes(x=grouping, y=0))

With facetting:

ggplot(dat, aes(letters,value, label = letters)) + 
     geom_bar(stat="identity") + 
     facet_wrap(~grouping, scales="free")

Facetting has the obvious advantage of not having to muck about with the positioning of the labels.

like image 102
Brandon Bertelsen Avatar answered Oct 18 '22 21:10

Brandon Bertelsen