用子组数和每个框的观察值标记箱线图
Label a Boxplot with number of subgroups and observations per box
我想制作一个箱线图,在其中用与该框相关的观察值数量以及与该框相关的子组数量标记每个框
我可以使用 ggplot2 包中包含的钻石数据集通过以下代码接近我想要的结果
data("diamonds")
n_fun <- function(x){
return(data.frame(y = 1,
label = length(x)))
}
ggplot(diamonds, aes(x=cut, y=price, fill=clarity)) +
geom_boxplot(position = position_dodge2(width=0.75, preserve='single')) +
theme_bw() +
stat_summary(fun.data = n_fun, geom = "text",aes(group=clarity),hjust = 0.5, position = position_dodge(0.6))
这给了我一个图表,其中显示了每个 "box" 的观察次数
我想做的是既显示观察次数又显示每个框中的颜色数,例如
Fair_I1<-subset(diamonds, cut=="Fair" & clarity=="I1")
table(Fair_I1$color)
显示在与 Fair-I1 相关的框中存在 7 个颜色组
因此最后一个示例将在图中的此框下方或上方同时显示 7(颜色数)和 210(观察值数)
您可以预先汇总数据,并将汇总数据传递给geom_text()
。在这里,我将值折叠到一个标签中,但您可以独立完成它们并放置单独的层,例如,如果您想要一组数字在顶部,另一组在底部。
library(ggplot2)
library(dplyr)
labeldat <- diamonds %>%
group_by(cut, clarity) %>%
summarise(labels = paste(n(), n_distinct(color), sep = "\n"))
ggplot(diamonds, aes(x=cut, y=price, fill=clarity)) +
geom_boxplot(position = position_dodge2(width=0.75)) +
theme_bw() +
geom_text(data = labeldat, aes(x = cut, y = -250, label = labels), hjust = 0.5, position = position_dodge2(width = .75))
我想制作一个箱线图,在其中用与该框相关的观察值数量以及与该框相关的子组数量标记每个框
我可以使用 ggplot2 包中包含的钻石数据集通过以下代码接近我想要的结果
data("diamonds")
n_fun <- function(x){
return(data.frame(y = 1,
label = length(x)))
}
ggplot(diamonds, aes(x=cut, y=price, fill=clarity)) +
geom_boxplot(position = position_dodge2(width=0.75, preserve='single')) +
theme_bw() +
stat_summary(fun.data = n_fun, geom = "text",aes(group=clarity),hjust = 0.5, position = position_dodge(0.6))
这给了我一个图表,其中显示了每个 "box" 的观察次数 我想做的是既显示观察次数又显示每个框中的颜色数,例如
Fair_I1<-subset(diamonds, cut=="Fair" & clarity=="I1")
table(Fair_I1$color)
显示在与 Fair-I1 相关的框中存在 7 个颜色组
因此最后一个示例将在图中的此框下方或上方同时显示 7(颜色数)和 210(观察值数)
您可以预先汇总数据,并将汇总数据传递给geom_text()
。在这里,我将值折叠到一个标签中,但您可以独立完成它们并放置单独的层,例如,如果您想要一组数字在顶部,另一组在底部。
library(ggplot2)
library(dplyr)
labeldat <- diamonds %>%
group_by(cut, clarity) %>%
summarise(labels = paste(n(), n_distinct(color), sep = "\n"))
ggplot(diamonds, aes(x=cut, y=price, fill=clarity)) +
geom_boxplot(position = position_dodge2(width=0.75)) +
theme_bw() +
geom_text(data = labeldat, aes(x = cut, y = -250, label = labels), hjust = 0.5, position = position_dodge2(width = .75))