问题描述
我喜欢使用 geom_density_ridges(),每个组也包含单独的点。但是,某些组的样本量较小(例如 n=1 或 2),因此无法生成密度脊。对于这些组,我希望能够绘制现有观测值的位置 - 即使 没有 概率密度函数将显示。
在本例中,我希望能够在适当的线上绘制 May 的 2 个数据点。
library(tidyverse)
library(ggridges)
data("lincoln_weather")
#pull weather from all months that are NOT May
lincoln_weather_nomay<-lincoln_weather[which(lincoln_weather$Month!="May"),]
#pull weather just from May
lincoln_weather_may<-lincoln_weather[which(lincoln_weather$Month=="May"),]
#recombine,keeping only the first two rows for the May dataset
new_weather<-rbind(lincoln_weather_nomay,lincoln_weather_may[c(1:2),])
ggplot( new_weather,aes(x=`Min Temperature [F]`,y=Month,fill=Month))+
geom_density_ridges(alpha = 0.5,jittered_points = TRUE,point_alpha=1,point_shape=21) +
labs(x="Average temperature (F)",y='')+
guides(fill=FALSE,color=FALSE)
如何将 May 观测的点添加到适当的位置(即 May 槽)以及沿 x 轴的适当位置?
解决方法
只需向该函数添加一个单独的 geom_point()
调用,您可以在其中对数据进行子集化以仅包括先前未绘制类别的观测值。您可以应用任何常见的自定义设置来“匹配”为其他类别绘制的点,或使这些点“突出”。
ggplot( new_weather,aes(x=`Min Temperature [F]`,y=Month,fill=Month))+
geom_density_ridges(alpha = 0.5,jittered_points = TRUE,point_alpha=1,point_shape=21) +
geom_point(data=subset(new_weather,Month %in% c("May")),aes(),shape=13)+
labs(x="Average temperature (F)",y='')+
guides(fill=FALSE,color=FALSE)