R 在第一个栏或更高位置写入组标签,而不是图例
我有一个包含以下数据的堆叠条形图R 在第一个栏或更高位置写入组标签,而不是图例,r,ggplot2,R,Ggplot2,我有一个包含以下数据的堆叠条形图 df <- expand.grid(name = c("oak","birch","cedar"), sample = c("one","two"), type = c("sapling","adult","dead")) df$count <- sample(5:200, size = nrow(df), replace = T) 它产生: 出现两到三个问题: 如何使标签仅显示在顶部栏中 如何使标签显示在条形图部分的中心 可选:
df <- expand.grid(name = c("oak","birch","cedar"),
sample = c("one","two"),
type = c("sapling","adult","dead"))
df$count <- sample(5:200, size = nrow(df), replace = T)
它产生:
出现两到三个问题:
上面有一个链接。那会对你有帮助的。在这里,我有另一个建议
set.seed(123)
df <- expand.grid(name = c("oak","birch","cedar"),
sample = c("one","two"),
type = c("sapling","adult","dead"))
df$count <- sample(5:200, size = nrow(df), replace = T)
### Arrange a data frame (summing up sample one and two)
library(dplyr)
ana <- df %>%
group_by(name, type) %>%
summarise(total = sum(count))
# Draw a figure once
bob <- ggplot(ana, aes(x = name, y = total, fill = type)) +
geom_bar(stat = "identity", position = "stack")
# Get a data frame for ggplot
cathy <- ggplot_build(bob)$data[[1]]
# calculate text position & add text labels
cathy$y_pos <- (cathy$ymin + cathy$ymax) / 2
cathy$label <- rep(c("sampling", "adult", "dead"), times = 3)
# Subset the data for labeling for the top bar
dan <- cathy[c(7:9), ]
# Draw a figure again
bob +
annotate(x = dan$x, y = dan$y_pos, label = dan$label, geom="text", size=3) +
coord_flip()
set.seed(123)
df应帮助您进行定位;对于仅标记选定的值,我将引入一个新的变量标签,该标签的类型值为cedar,而其他树为空。我猜想,不可能将标签放在顶部栏的上方,并通过箭头将其组合到其栏部分?MS Excel可以(尽管不一定适用于堆叠的条形图)。@MERose您可以将图例移动到顶部位置。但是我不认为ggplot
有箭头的东西。
set.seed(123)
df <- expand.grid(name = c("oak","birch","cedar"),
sample = c("one","two"),
type = c("sapling","adult","dead"))
df$count <- sample(5:200, size = nrow(df), replace = T)
### Arrange a data frame (summing up sample one and two)
library(dplyr)
ana <- df %>%
group_by(name, type) %>%
summarise(total = sum(count))
# Draw a figure once
bob <- ggplot(ana, aes(x = name, y = total, fill = type)) +
geom_bar(stat = "identity", position = "stack")
# Get a data frame for ggplot
cathy <- ggplot_build(bob)$data[[1]]
# calculate text position & add text labels
cathy$y_pos <- (cathy$ymin + cathy$ymax) / 2
cathy$label <- rep(c("sampling", "adult", "dead"), times = 3)
# Subset the data for labeling for the top bar
dan <- cathy[c(7:9), ]
# Draw a figure again
bob +
annotate(x = dan$x, y = dan$y_pos, label = dan$label, geom="text", size=3) +
coord_flip()