2

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

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Nice solution with the facets! Maybe you could use scales = "free_x" for better comparability, but I think this is also a bit a personal choice
@starja I absolutely agree with you. It depends of personal choice. Also, your answer is nice :)
Thanks a lot Duck. I would have to rescale the axes, but this could work.
3

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)

2 Comments

Thanks a bunch Starja! This is exactly the solution I was looking for. I saw in the vignette that there was a group argument, but coundn't figure out how it was working.
Glad to help! If you don't want the animals to have different colours, you can use group instead of fill; and with geom_col(width = 0.8, position = position_dodge(width = 0.9)) you can tweak the spacing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.