user13608970
user13608970

Reputation: 197

How to create a 2 variable barplot using ggplot2 in r

I have a data frame and i want to plot a bar chart with two numerical values bars side by side namely Mean_dbh and Low_AGC for each given location (SU) How do i plot this using ggplot2

   SU Mean_dbh   Low_AGC
1   1 16.98921 17.696251
2   2 13.48199  8.108352
3   3 15.97746 14.584501
4   4 12.14046 28.910114
5   5 16.47509 38.047385
6   6 19.80792 31.183069
7   7 17.44469 38.192385
8   8 18.78043 12.138436
9  10 15.68889 24.195719
10 11 17.39620 26.621287
11 15 16.71296 32.219763

Upvotes: 0

Views: 54

Answers (1)

MarBlo
MarBlo

Reputation: 4534

By using tidyverse and pivot_longer you can merge the two variables. geom_col allows to define SU as the x-axis and the value of merged variable as the y-axis. The color is defined by fill=name where name is the merged column. Axis are renamed to make things clear.

library(tidyverse)

df <- read.table(text = "   SU Mean_dbh   Low_AGC
1   1 16.98921 17.696251
2   2 13.48199  8.108352
3   3 15.97746 14.584501
4   4 12.14046 28.910114
5   5 16.47509 38.047385
6   6 19.80792 31.183069
7   7 17.44469 38.192385
8   8 18.78043 12.138436
9  10 15.68889 24.195719
10 11 17.39620 26.621287
11 15 16.71296 32.219763", header=T)
df
#>    SU Mean_dbh   Low_AGC
#> 1   1 16.98921 17.696251
#> 2   2 13.48199  8.108352
#> 3   3 15.97746 14.584501
#> 4   4 12.14046 28.910114
#> 5   5 16.47509 38.047385
#> 6   6 19.80792 31.183069
#> 7   7 17.44469 38.192385
#> 8   8 18.78043 12.138436
#> 9  10 15.68889 24.195719
#> 10 11 17.39620 26.621287
#> 11 15 16.71296 32.219763

ggplot(df %>% pivot_longer(cols = Mean_dbh:Low_AGC),
       aes(x=SU, y = value, fill=name)) +geom_col(position = 'dodge') +
  labs(x='Location', y='Mean_dbh or Low_AGC') +
  theme(legend.title = element_blank())

Upvotes: 1

Related Questions