Home > OS >  How to put two variables into one ggplot
How to put two variables into one ggplot

Time:08-10

Dataset: data

Region Forest Lakes
North 30 40
West 40 100
South 12 30
Central 44 200
data %>%
  ggplot(aes(x = Region, y = Forest))  
  geom_col()  
  facet_wrap(~Lakes)    ggtitle("Lakes and Forest in different Regions")

Unfortunately this is not the right thing.

I would like to show for each region how much lakes and forests they have and then the nearest region in x-axis. How does it work?

CodePudding user response:

Reshape to 'long' format with pivot_longer and then use geom_col with position='dodge'

library(dplyr)
library(tidyr)
library(ggplot2)
data %>% 
  pivot_longer(cols = Forest:Lakes) %>%
  ggplot(aes(x = Region, y = value, fill = name))   
  geom_col(position = 'dodge')    
  ggtitle("Lakes and Forest in different Regions")
  •  Tags:  
  • r
  • Related