[英]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我有一个数据框,我想 plot 一个条形图,其中有两个数值条并排,即每个给定位置的 Mean_dbh 和 Low_AGC (SU) 我如何使用 plot 这个使用 Z64B86077DA4139166463CZ271
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
By using tidyverse
and pivot_longer
you can merge the two variables.通过使用tidyverse
和pivot_longer
,您可以合并这两个变量。 geom_col
allows to define SU as the x-axis and the value of merged variable as the y-axis. geom_col
允许将SU定义为 x 轴,并将合并变量的值定义为 y 轴。 The color is defined by fill=name
where name is the merged column.颜色由fill=name
定义,其中name是合并的列。 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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.