0

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

1 Answer 1

1

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())

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

3 Comments

I get the following error when storing df Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec, : line 1 did not have 4 elements
@user13608970 Not sure why you want to do this. As the documentation says with scan you do: Read data into a vector or list from the console or file. . If you want to store the df you can store it to rds format with saveRDS.
My wording was wrong. Sorry. I meant that when I run your suggested code I get the particular warning

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.