英文:
Plot count each boxplot at the base of each facet using geom_boxplot
问题
我想绘制每个分面中的箱线图上方的数据统计信息。以下是你提供的代码的翻译:
需要(tidyverse)
ggplot(mtcars, aes(x = cyl, y = mpg, group = cyl)) +
geom_boxplot(aes(fill = cyl), outlier.size = 1, outlier.shape = 16,
show.legend = FALSE, lwd = 0.2) + # 绘制箱线图
facet_wrap(gear ~ ., nrow = 1, scales = "free") +
stat_summary(fun.data = give.n, geom = "text", fun.min = -Inf,
size = 5, colour = "red", hjust = 0)
请注意,我只翻译了你提供的代码部分,不包括问题描述。
英文:
I would like to plot the tally of data informing each boxplot in a facet-wrapped geom_boxplot.
The example below gives the count below each boxplot but I would like to align the counts, ideally just above with the minimum of each facet when scales are set as free. While the last item gives the counts I don't understand how it decides the y-value for the plotting in each case.
require(tidyverse)
ggplot(mtcars, aes(x = cyl, y = mpg, group = cyl)) +
geom_boxplot(aes(fill = cyl), outlier.size = 1, outlier.shape = 16,
show.legend = FALSE, lwd = 0.2) + # Make box plots
facet_wrap(gear ~ ., nrow = 1, scales = "free") +
stat_summary(fun.data = give.n, geom = "text", fun.min = -Inf,
size = 5, colour = "red", hjust = 0)
答案1
得分: 1
你可以使用geom_text()
来实现这个功能。在渲染箱线图之前,你可以手动计算每个子图中最小值的位置。以下是代码的翻译部分:
library(ggplot2)
library(dplyr)
give.n = mtcars %>%
mutate(y_label_min = min(mpg), .by = gear) %>%
summarise(
y_label_min = min(y_label_min),
n = n(),
.by = c(gear, cyl)
)
ggplot(mtcars, aes(x = cyl, y = mpg, group = cyl)) +
geom_boxplot(aes(fill = cyl), outlier.size = 1, outlier.shape = 16,
show.legend = FALSE, lwd = 0.2) + # 绘制箱线图
facet_wrap(gear ~ ., nrow = 1, scales = "free") +
geom_text(
data = give.n,
aes(label = n, x = cyl, y = y_label_min)
)
请注意,我只翻译了你提供的代码部分,没有包括问题或其他内容。
英文:
You could do with geom_text()
.
You could manually calculate 'just above with the minimum of each facet' before rendering the boxplot.
library(ggplot2)
library(dplyr)
give.n = mtcars |>
mutate(y_label_min = min(mpg), .by=gear) |> # Dplyr 1.1.0
summarise(
y_label_min = min(y_label_min),
n = n(),
.by = c(gear ,cyl)
)
ggplot(mtcars, aes(x = cyl, y = mpg, group = cyl)) +
geom_boxplot(aes(fill = cyl), outlier.size = 1, outlier.shape = 16,
show.legend = FALSE, lwd = 0.2) + # Make box plots
facet_wrap(gear ~ ., nrow = 1, scales = "free")+
geom_text(
data=give.n,
aes(label=n,x=cyl, y=y_label_min)
)
<!-- -->
<sup>Created on 2023-05-07 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论