![](/img/trans.png)
[英]Plotting Grouped Bar Chart with variables sharing the same time index (grouped bar chart) R
[英]Error in height for plotting grouped bar chart in R
我正在嘗試使用我的 excel 表中的以下數據集按場景創建分組條形圖:
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 軸應該是場景類型,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())
ggplot
解決方案將意味着 pivot 您的 dataframe 轉換為更長的格式,例如:
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())
使用barplot
的基本 r 解決方案將意味着轉置您的 dataframe 並轉換為矩陣,如下所示:
rownames(df) <- df$Scenerio
df <- t(df[,-1])
colnames(df) <- 1:9
barplot(df, beside = TRUE, legend = rownames(df),
xlab = "Scenario", ylab = "Score")
可重現的例子
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"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.