我目前有一个结构为as below的数据框:
Establishment.date Species Shade.Tol Ele Kipuka
1 1980 PSEMEN Intolerant Under 1050m On Kipuka
2 1981 PINCON Intolerant Above 1050m On Kipuka
3 1981 ABIPRO Intolerant Under 1050m On Kipuka
4 1981 ABIPRO Intolerant Under 1050m On Kipuka
5 1981 ABILAS Tolerant Above 1050m On Kipuka
6 1982 ABILAS Tolerant Above 1050m On Kipuka
7 1983 PSEMEN Intolerant Under 1050m On Kipuka
8 1984 TSUHET Tolerant Under 1050m On Kipuka
9 1984 TSUHET Tolerant Under 1050m On Kipuka
10 1984 PSEMEN Intolerant Under 1050m On Kipuka
11 1984 PINCON Intolerant Under 1050m On Kipuka
12 1984 ABIPRO Intolerant Above 1050m On Kipuka
13 1984 ABIPRO Intolerant Above 1050m On Kipuka
我正试图绘制一个条形图,以突出显示在高低两面都由其阴影耐受性所引起的场所数量,并将每个类别的数量显示为标签。我当前的方法是过滤数据框,使其具有as below如下的新汇总数据框:
# A tibble: 9 x 4
# Groups: Establishment.date, Shade.Tol [7]
Establishment.date Shade.Tol Ele count
<int> <fct> <fct> <int>
1 1980 Intolerant Under 1050m 1
2 1981 Intolerant Above 1050m 1
3 1981 Intolerant Under 1050m 2
4 1981 Tolerant Above 1050m 1
5 1982 Tolerant Above 1050m 1
6 1983 Intolerant Under 1050m 1
7 1984 Intolerant Above 1050m 2
8 1984 Intolerant Under 1050m 2
9 1984 Tolerant Under 1050m 2
并按照以下步骤将新信息绘制到ggplot中:
cores_clean %>%
group_by(Establishment.date,Shade.Tol,Ele) %>%
summarise(count = n()) %>%
ggplot(aes(x = Ele, y=count, label=count)) +
geom_bar(stat = "identity",position = "dodge") +
geom_text(aes(label=count),size = 3)+
facet_wrap(~ Shade.Tol)+
#scale_fill_grey()+
theme_bw() +
labs(x = "Elevation Range",
y = "Count",
title = "Establishments")+
theme(plot.title = element_text(hjust = 0.5))
但是当我运行代码时,图形输出会打印出如下所示的一堆值,
不代表在数据帧中找到的那些(n = 740)。我尝试添加geom_text(aes(label=sum(count)))
,但打印出相同的数字位置,并且观察的总数重复了多次。不知道我是过滤数据错误还是没有正确将其添加到ggplot中。
答案 0 :(得分:1)
您的主要问题是您group_by(Estabilishment.date)
,但您似乎根本不想在图表中看到它。这是一个使用stat_summary
来计算总和的选项:
cores_clean %>%
group_by(Establishment.date,Shade.Tol,Ele) %>%
dplyr::summarise(count = n()) %>%
ggplot(aes(x = Ele, y=count, fill = as.factor(Establishment.date))) +
geom_bar(stat = "identity") +
stat_summary(geom = "text", aes(label = ..y.., group = Ele),
fun = sum, vjust = -0.1) +
facet_wrap(~ Shade.Tol) +
theme_bw() +
labs(x = "Elevation Range", y = "Count",
title = "Establishments", fill = "Year")+
theme(plot.title = element_text(hjust = 0.5))
或者,您可以从Estabilishment.date
中删除group_by
并执行以下操作:
cores_clean %>%
group_by(Shade.Tol,Ele) %>%
dplyr::summarise(count = n()) %>%
ggplot(aes(x = Ele, y=count)) +
geom_bar(stat = "identity") +
stat_summary(geom = "text", aes(label = ..y.., group = Ele),
fun = sum, vjust = -0.1) +
facet_wrap(~ Shade.Tol) +
theme_bw() +
labs(x = "Elevation Range", y = "Count",
title = "Establishments")+
theme(plot.title = element_text(hjust = 0.5))