我有一张小桌子,像这样:
我希望将此信息绘制为R中的分组条形图。但是,为了使此信息正常工作,在yes / no列上方需要一个“成功”行,这在excel中很容易做到,但是我不确定如何放在R。这是我目前的代码。如何在“否/是”列的上方添加一行?
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函数collect进行,下面的代码将帮助您完成所需的操作。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句