英文:
How to add an annotation that calculates a value as part of plot composition?
问题
使用ggplot,我想要添加一个_注释_,描述轴的平均值,并且希望进行即时计算,而不是将值分配给专用对象的预先计算。
示例
考虑以下按cut
划分的carat
直方图:
library(ggplot2)
library(dplyr)
diamonds |>
filter(depth > 60) |>
ggplot(aes(carat)) +
geom_histogram() +
stat_summary(aes(xintercept = after_stat(x), y = 0),
fun = mean,
geom = "vline",
orientation = "y",
color = "red") +
facet_wrap(~cut)
创建于2023-07-13,使用reprex v2.0.2
期望的输出
我是否可以在ggplot组合中添加另一行代码,以添加一个注释,显示"平均克拉 = mean(carat)"
,并且它将按facet进行平均计算?
伪代码
英文:
Using ggplot, I want to add an annotation that describes the mean value of an axis, and I wish to make this calculation on the fly, rather than a preemptive calculation that assigns a value to a dedicated object.
Example
Consider the following carat
histogram by cut
:
library(ggplot2)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
diamonds |>
filter(depth > 60) |>
ggplot(aes(carat)) +
geom_histogram() +
stat_summary(aes(xintercept = after_stat(x), y = 0),
fun = mean,
geom = "vline",
orientation = "y",
color = "red") +
facet_wrap(~cut)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
<!-- -->
<sup>Created on 2023-07-13 with reprex v2.0.2</sup>
Desired Output
Can I tuck another line of code to the ggplot composition that will add an annotation for "Mean Carat = mean(carat)"
and it will do the mean calculation per facet?
Pseudo Plot
答案1
得分: 3
基本上与vline
相同,但我们必须使用geom="text"
并在label
aes上映射:
library(ggplot2)
library(dplyr, warn = FALSE)
diamonds |>
filter(depth > 60) |>
ggplot(aes(carat)) +
geom_histogram() +
stat_summary(aes(xintercept = after_stat(x), y = 0),
fun = mean,
geom = "vline",
orientation = "y",
color = "red"
) +
stat_summary(
aes(
label = after_stat(paste0("均值克拉 = ", round(x, 3))),
y = 6000
),
fun = mean,
geom = "text",
orientation = "y",
color = "red",
hjust = 0,
position = position_nudge(x = .1)
) +
facet_wrap(~cut)
英文:
It's basically the same as for the vline
but instead we have to use geom="text"
and map on the label
aes:
library(ggplot2)
library(dplyr, warn = FALSE)
diamonds |>
filter(depth > 60) |>
ggplot(aes(carat)) +
geom_histogram() +
stat_summary(aes(xintercept = after_stat(x), y = 0),
fun = mean,
geom = "vline",
orientation = "y",
color = "red"
) +
stat_summary(
aes(
label = after_stat(paste0("Mean Carat = ", round(x, 3))),
y = 6000
),
fun = mean,
geom = "text",
orientation = "y",
color = "red",
hjust = 0,
position = position_nudge(x = .1)
) +
facet_wrap(~cut)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论