hani eh
hani eh

Reputation: 11

plot with two columns side by side in R

I'm new to coding so this question might seem dumb to others.

I'm trying to recreate this plot in R: enter image description here

My code is:

population <- c(894, 15736, 42147)
household <- c(215, 4357, 13622)
year <- c(2000, 2010, 2020)
df <- data.frame(year, population, household)

library(ggplot2)

pl <- ggplot(df, aes(x= factor(year), y= factor(population), fill= factor(household)))
pl2 <- pl+ geom_col(position="Dodge")+ labs(x="Year", y= "Population")


print(pl2)

and that's the result: enter image description here As you can see the household column doesn't appear as a column here, although I'm using dodge position. I can't figure out what the problem is. I'd appreciate any helps.

Upvotes: 1

Views: 1659

Answers (1)

Bast_B
Bast_B

Reputation: 143

I think what you are trying to do is something like that :

population <- c(894, 15736, 42147)
household <- c(215, 4357, 13622)
year <- c(2000, 2010, 2020)
df <- data.frame(year, population, household)

library(tidyr)
df=df%>%pivot_longer(!year)
library(ggplot2)

pl <- ggplot(df, aes(x= year, y=value,fill= name))
pl2 <- pl+ geom_col(position="Dodge")+ labs(x="Year", y= "Population")


print(pl2)

enter image description here

From your code I would do :

pl2=ggplot(df, aes(x= factor(year), y=value,fill= name))+
 geom_bar(stat='identity',position = "dodge")+ labs(x="Year", y= "Population")+
  theme_bw()+
  geom_text(aes(label = value),position=position_dodge(width=0.9),size = 4,vjust=-0.5)
print(pl2)

This way you have number above column (theme_bw gives a nice looking plot but it is personnal taste)

Upvotes: 2

Related Questions