[英]Plotting a grouped bar plot in R when you have yes/no columns
我有一個像這樣的小桌子:
我希望將此信息繪制為 R 中的分組條形圖。 然而,為了使其正常工作,是/否列上方需要一個“成功”行,這在 excel 中很容易做到,但我不知道如何把它放在 R 中。這是我目前的代碼。 如何在 no/yes 列的上方添加一行?
status1 <- c("currently", "missing", "never", "previously")
no1 <- c(107, 8, 131, 142)
yes1 <- c(104, 8, 232, 132)
tata <- data.frame(status1, no1, yes1)
ggplot(tata, aes(fill=yes1, y=no1, x=status1)) +
geom_bar(position="dodge", stat="identity")
您需要將數據從寬格式轉換為長格式,這可以使用 tidyr 函數收集,下面是幫助您完成所需的代碼。
library(tidyr)
library(dplyr)
library(ggplot2)
status1 <- c("currently", "missing", "never", "previously")
no1 <- c(107, 8, 131, 142)
yes1 <- c(104, 8, 232, 132)
tata <- data.frame(status1, no1, yes1)
tata %>%
gather(key = "success", value = value, -status1) %>%
ggplot(aes(y = value, x = status1, fill = success)) +
geom_bar(position = "dodge", stat = "identity")
要播放並向圖表添加一些標題,您可以執行以下操作
tata %>%
gather(key = "success", value = value, -status1) %>%
ggplot(aes(y = value, x = status1, fill = success)) +
geom_bar(position = "dodge", stat = "identity") +
xlab("Status") + # To change x- axis
ylab("Number of People") + # To change y-axis
ggtitle("Success Analysis") + # To change title
labs(fill = "Success Legend") + # To change legend title
scale_fill_manual(labels = c("No", "Yes"), values = c("orange", "green")) # To change legend values titles and their colours
我認為您需要以更長的格式重塑數據。 您可以使用pivot_longer
函數來tidyr
:
library(tidyr)
tata %>% pivot_longer(., -status1, names_to = "variable", values_to = "values")
# A tibble: 8 x 3
status1 variable values
<fct> <chr> <dbl>
1 currently no1 107
2 currently yes1 104
3 missing no1 8
4 missing yes1 8
5 never no1 131
6 never yes1 232
7 previously no1 142
8 previously yes1 132
然后,您可以使用是/否作為 x 軸繪制數據,如下所示:
library(tidyr)
tata %>% pivot_longer(., -status1, names_to = "variable", values_to = "values") %>%
ggplot(., aes(x = variable, y = values, fill = status1))+
geom_bar(stat = "identity", position = position_dodge())
或使用 status1 作為 x 軸
library(tidyr)
tata %>% pivot_longer(., -status1, names_to = "variable", values_to = "values") %>%
ggplot(., aes(x = status1, y = values, fill = variable))+
geom_bar(stat = "identity", position = position_dodge())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.