我的 R geom_bar 图例中的"N = 1"框是什么,如何删除?



这些是数据:

structure(list(Group.1 = c((name list)
), Group.2 = structure(c(4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 
4L, 4L, 3L, 3L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 5L, 5L, 5L, 1L, 1L, 
1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Radio", "Video", "Engineering", 
"800Mhz", "PSSRP", "Other"), class = "factor"), x = c(93.5, 208.75, 
214, 48, 66.33, 71.5, 19.5, 64.75, 17, 39, 30.75, 96.75, 30, 
19, 32.5, 12.75, 47.25, 14, 22.25, 12, 3, 128.5, 9.5, 303.2, 
290.35, 364.05, 333.25, 11.75, 553.25, 423, 6, 496)), .Names = c("Group.1", 
"Group.2", "x"), row.names = c(NA, -32L), class = "data.frame")

运行此图:

ggplot(data = HrSums, aes(x = Group.1, y = x, fill = Group.2)) +
geom_bar(stat = "sum", position = position_stack(reverse = TRUE)) + 
coord_flip() + 
labs(title = "Hours Billed, by Technician and Shop", y = "Hours Billed", 
x = "Technician", fill = "Shop")

我得到这个条形图:

什么是"n"框,如何(仅)从图例中删除它?

如果包含以下内容,则只会看到所期望的美学:

show.legend = c(
"x" = TRUE,
"y" = TRUE,
"alpha" = FALSE,
"color" = FALSE,
"fill" = TRUE,
"linetype" = FALSE, 
"size" = FALSE, 
"weight" = FALSE
)

请参阅有关 ?geom_bar 的 show.legend 参数:

显示.传奇逻辑。此图层是否应包含在图例中? NA(默认值)包括是否映射了任何美学。错误从不 包含,并且 TRUE 始终包含。它也可以是命名逻辑 矢量以精细选择要显示的美学

我相信n 框是因为geom_bar希望计算每个Group.1Group.2组合出现的次数,但相反,您在aes中给出了一个y值。geom_bar可以使用不同的统计数据而不是计数,但如果你想要值的总和,它需要weight美感。这里有两种方法可以做到这一点,一种是在geom_bar中使用weight = x,另一种是使用dplyr函数事先计算总和,然后将其提供给y

library(tidyverse)

ggplot(df, aes(x = Group.1, fill = Group.2)) +
geom_bar(aes(weight = x), position = position_stack(reverse = T)) +
coord_flip()


df_sums <- df %>%
group_by(Group.1, Group.2) %>%
summarise(x = sum(x))
ggplot(df_sums, aes(x = Group.1, y = x, fill = Group.2)) +
geom_col(position = position_stack(reverse = T)) +
coord_flip()

相关内容

最新更新