如何将stat_summary行添加到ggplot2中的coord_polar图中?

时间:2016-08-15 09:59:36

标签: r ggplot2

我在facet_grid中排列了莲座图,显示了2x2析因实验的直方图数据。模拟此处生成的数据:

#GENERATE MOCK DATA-------------------------------------------------------------------------
Treatment <- c(rep("Vehicle", 50), rep("Drug", 50))
Cell <- c(rep("A", 25), rep("B", 25), rep("A", 25), rep("B", 25))
Response <- c(rnorm(25, 50, 120), rnorm(25, 30, 90), rnorm(25, 50, 120), rnorm(25, 30, 90))
Data <- data.frame(Treatment, Cell, Response)

然后我生成这样的玫瑰花图:

#PLOT ROSETTES-------------------------------------------------------------------------------
library("ggplot2")
baseplot <- ggplot(data = Data, aes(x = Response, fill = Treatment))
baseplot + geom_bar(width = 4) + coord_polar() + facet_grid(Treatment~Cell) +
labs(y = "Frequency", x = "")

Here is an image of the plot(实际的情节更令人愉悦,为了演示的目的,我忽略了重叠条的错误。)

我想在每个方面添加一条线,从中心向外辐射,标记每个因素组合的中位数。我尝试使用stat_summary执行此操作,方法如下:

+ stat_summary(fun.y = "median", geom = "line)

但我收到以下错误:

警告讯息:

1:在is.na(x)中:is.na()应用于'NULL'类型的非(列表或向量)

2:stat_summary()中的计算失败: 参数意味着不同的行数:1,0

3:在is.na(x)中:is.na()应用于'NULL'类型的非(列表或向量)

4:stat_summary()中的计算失败: 参数意味着不同的行数:1,0

5:在is.na(x)中:is.na()应用于'NULL'类型的非(列表或向量)

6:stat_summary()中的计算失败: 参数意味着不同的行数:1,0

7:在is.na(x)中:is.na()应用于'NULL'类型的非(列表或向量)

8:stat_summary()中的计算失败: 参数意味着不同的行数:1,0

我知道可能有一个简单的解决方案,但我一直在努力理解stat_summary的语法。如果你能提供任何帮助,我会很高兴。我甚至不介意首先手动计算中位数并添加它们。

1 个答案:

答案 0 :(得分:2)

可能会有一个很好的stat_summary答案,但我没有看到它,因为您需要访问..count..生成的geom_bar。另请注意,geom_line需要多个点来绘制一条线,而median只会提供一个值。

我似乎更容易预先计算不同的中位数,并使用geom_vline将它们添加到情节中。这对dplyr很方便。

library(dplyr)
Data2 <- Data %>% 
  group_by(Cell, Treatment) %>% 
  summarize(v = median(Response))

制作情节:

library(ggplot2)
baseplot <- ggplot(data = Data, aes(x = Response, fill = Treatment))
baseplot + geom_bar(width = 4) + coord_polar() + facet_grid(Treatment~Cell) +
  labs(y = "Frequency", x = "") + 
  geom_vline(data = Data2, aes(xintercept = v), size = 1.5)

结果:

enter image description here

相关问题