R 如何用ggplot2显示小提琴图上最高密度点的Y值?
让我们以docs的ggplot2小提琴图示例中的数据集为例R 如何用ggplot2显示小提琴图上最高密度点的Y值?,r,ggplot2,violin-plot,R,Ggplot2,Violin Plot,让我们以docs的ggplot2小提琴图示例中的数据集为例 > ToothGrowth$dose <- as.factor(ToothGrowth$dose) > head(ToothGrowth) len supp dose 1 4.2 VC 0.5 2 11.5 VC 0.5 3 7.3 VC 0.5 4 5.8 VC 0.5 5 6.4 VC 0.5 6 10.0 VC 0.5 >牙齿生长$剂量头(牙齿生长) 透镜补充剂
> ToothGrowth$dose <- as.factor(ToothGrowth$dose)
> head(ToothGrowth)
len supp dose
1 4.2 VC 0.5
2 11.5 VC 0.5
3 7.3 VC 0.5
4 5.8 VC 0.5
5 6.4 VC 0.5
6 10.0 VC 0.5
>牙齿生长$剂量头(牙齿生长)
透镜补充剂量
1 4.2 VC 0.5
2 11.5 VC 0.5
3.7.3风险资本0.5
4.5.8 VC 0.5
5.6.4 VC 0.5
6 10.0 VC 0.5
如果我们绘制图表
library(ggplot2)
# Basic violin plot
p <- ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_violin()
p
# Rotate the violin plot
p + coord_flip()
# Set trim argument to FALSE
ggplot(ToothGrowth, aes(x=dose, y=len)) +
geom_violin(trim=FALSE)
库(ggplot2)
#小提琴基本情节
你是说像这样的事吗
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
geom_violin(trim = FALSE) +
geom_text(
data = ToothGrowth %>%
group_by(dose) %>%
summarise(len = mean(len)),
aes(x = as.factor(dose), y = len, label = len))
更新
要打印最大(密度)的位置,可以执行以下操作
ggplot(ToothGrowth, aes(x = as.factor(dose), y = len)) +
geom_violin(trim = FALSE) +
geom_text(
data = ToothGrowth %>%
group_by(dose) %>%
nest() %>%
transmute(dose, len = map_dbl(data, function(x) {
dens <- density(x$len)
dens$x[which.max(dens$y)] })),
aes(x = as.factor(dose), y = len, label = sprintf("%4.3f", len)))
ggplot(牙齿生长,不良事件(x=as.因子(剂量),y=len))+
geom_小提琴(修剪=假)+
geom_文本(
数据=增长%>%
组别(剂量)%>%
嵌套()%>%
转化(剂量,len=map_dbl)(数据,函数(x){
dens No.我想你是在打印平均值。但我想要的是图中有峰值的值。因此在0.5的情况下,它应该略小于10。使用内置的摘要可能更容易,例如geom_text(aes(label=round(stat(y),3)),stat='summary',fun.y='mean')
。或者对于密度:geom_text(aes)(label=round(stat(y)),3)),stat='summary',fun.y=函数(x){d