Group variables in ggplot2 (geom_col)

I want to plot variables from a dataframe into different groups, but cannot figure out how to do this.

Mock data frame:

df<-data.frame(animal=c("cat1","cat2","mouse1","mouse2","dog1","dog2"),size=c(3,4,1,2,6,7))
plot<-ggplot(df)+geom_col(mapping=aes(x=animal,y=size))
plot 

current output

My wanted output should look like this:

wanted output

Upvotes: 2

Views: 2465

Answers (2)

starja
starja

Reputation: 10365

You need to tell ggplot to which group an animal belongs to; then you can use the group argument on the x-axis and use the fill argument to further distinguish between the different animals. position = "dodge" leads to the bars showing up next to each other.

library(ggplot2)
df <- data.frame(animal = c("cat1","cat2","mouse1","mouse2","dog1","dog2"),
                 size=c(3,4,1,2,6,7),
                 group = c("cat", "cat", "mouse", "mouse", "dog", "dog"))

ggplot(df, aes(x = group, y = size, fill = animal)) +
  geom_col(position = "dodge")

Created on 2020-08-23 by the reprex package (v0.3.0)

Upvotes: 3

Duck
Duck

Reputation: 39595

I would suggest next approach. You have to create a group and then use facets. Most of these tricks I learnt from @AllanCameron that has great answer for problems of this style.Next the code that can do that:

library(tidyverse)
#Data
df<-data.frame(animal=c("cat1","cat2","mouse1","mouse2","dog1","dog2"),
               size=c(3,4,1,2,6,7),stringsAsFactors = F)
#Create group
df$Group <- gsub('\\d+','',df$animal)
#Now plot
ggplot(df,aes(x=animal,y=size))+
  geom_col()+
  facet_wrap(.~Group,scales = 'free', strip.position = "bottom")+
  theme(strip.placement  = "outside",
        panel.spacing    = unit(0, "points"),
        strip.background = element_blank(),
        strip.text       = element_text(face = "bold", size = 12),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

The output:

enter image description here

Upvotes: 4

Related Questions