在R中绘制分组条形图的高度误差

问题描述 投票:1回答:1

我正在尝试使用我的Excel工作表中的以下数据集按Scenerio创建分组的条形图:

Scenerio Migration  Foraged Counter
1            0        741    1500
2            1        740    1500
3           200       475    1349
4           198       215    832
5           184       118    616
6           151        52    412
7           139        31    343
8           134        21    304
9           131        14    278

我的x轴应该是Scenerio类型,而y轴应该是平均分数。分组的列应进行迁移和搜寻。我尝试以几种不同的方式运行此方法,但始终收到此错误'height' must be a vector or a matrix。如何使用此数据集制作分组的条形图?

这里只是几次尝试:

   1.  barplot(dat, col = c("darkblue", "red"), beside = TRUE, legend = rownames (dat))

   2.  barplot(dat, beside = T, ylim = c(0,1600), col = dat$Scenerio, axis.lty = "solid")

3. condition <- c(dat$Migration, dat$Foraged)
ggplot(dat, aes(x=dat$Scenerio, y=dat$Counter, fill=condition)) +geom_bar(position = position_dodge())
r plot bar-chart
1个回答
0
投票

ggplot解决方案将意味着将数据框转换为更长的格式,例如:

library(tidyr)
library(dplyr)
library(ggplot2)

df %>% pivot_longer(-Scenerio) %>%
  ggplot(aes(x = as.factor(Scenerio), y = value, fill = name))+
  geom_col(position = position_dodge())

enter image description here

使用barplot的基本解将隐含转置您的数据帧并按如下所示转换为矩阵:

rownames(df) <- df$Scenerio
df <- t(df[,-1])
colnames(df) <- 1:9

barplot(df, beside = TRUE, legend = rownames(df), 
        xlab = "Scenario", ylab = "Score")

enter image description here


可复制的示例

structure(list(Scenerio = 1:9, Migration = c(0L, 1L, 200L, 198L, 
184L, 151L, 139L, 134L, 131L), Foraged = c(741L, 740L, 475L, 
215L, 118L, 52L, 31L, 21L, 14L), Counter = c(1500L, 1500L, 1349L, 
832L, 616L, 412L, 343L, 304L, 278L)), row.names = c(NA, -9L), class = c("data.table", 
"data.frame"))
© www.soinside.com 2019 - 2024. All rights reserved.