如何避免stat_summary更改y轴范围?

时间:2020-03-10 03:49:39

标签: r ggplot2

我以所需的代码为例设置了图表。

dates <- seq(as.Date("2019-04-01"), as.Date("2019-04-30"), "days")
fastTimes <- seq(40, 60, 1)
slowTimes <- seq(55, 75, 1)
times <- c(fastTimes, slowTimes)

nBob <- 500
nJane <- 1500
n <- nBob + nJane
cNames <- c(rep("Bob", nBob), rep("Jane", nJane))
cDates <- sample(dates, n, replace = TRUE)
cTimes <- sample(times, n, replace = TRUE)


df <- data.frame(cNames, cDates, cTimes)

mapping <- aes(x = cNames, y = cTimes)
ggplot(df, mapping) + geom_violin(scale = "area") + coord_flip()

我想给每个小提琴加一个标签,并附上样品数量。我已经更新了完整的绘图调用,如下所示,它在所需的位置创建了所需的标签。但是它会移动y轴的最小值/最大值以包括样本数。也就是说,它从0更改为1500,而不是40更改为80。

ggplot(df, mapping) + geom_violin(scale = "area") + coord_flip() +
  stat_summary(fun = mean, fun.max = length, geom = "text", aes(label = ..ymax..), color = "black",  vjust = -1)

如何在不更改y轴缩放比例的情况下添加标签?

谢谢

编辑:这是我添加stat_summary调用后的样子。

enter image description here

1 个答案:

答案 0 :(得分:2)

似乎您在fun.max函数中调用stat_summary时,将图扩展到该特定y值。

您可以使用stat_summary而不是使用geom_text并通过使用dplyr软件包来动态计算每个组的长度(并设置它们的x,y位置),例如:

library(dplyr)
library(ggplot2)
ggplot(df, aes(x = cNames, y = cTimes))+
  geom_violin(scale = "area")+
  geom_text(inherit.aes = FALSE, 
            data = df %>% group_by(cNames) %>% summarise(Nb = n(), Mean = mean(cTimes)), 
            aes(x = cNames, y = Mean, label = Nb), color = "black", vjust = -1)+
  coord_flip()

enter image description here

它回答了您的问题吗?

相关问题