如何按变量设置ggridges绘图的点形状与填充颜色?
Customizing Point Shapes & Fills in ggridridges for Grouped Data
Got it! Since you're using the development version of ggridridges (which adds point display functionality), we can directly map your gender group to point_shape and point_fill to get the exact styling you want—green squares for females, blue triangles for non-females. Here's a step-by-step solution tailored to your needs:
Step 1: Simulate Your Data
First, let's create a reproducible sample dataset matching your use case:
library(ggplot2) library(ggridridges) # Set seed for consistent results set.seed(123) df <- data.frame( gender = rep(c("Female", "Non-Female"), each = 200), metric_value = c(rnorm(200, mean = 5), rnorm(200, mean = 7)), category = rep(1:10, 40) )
Step 2: Build the Ridge Plot with Custom Points
We’ll map the gender variable to both point_shape and point_fill, then use manual scales to define your preferred styles:
ggplot(df, aes(x = metric_value, y = category, group = gender, point_shape = gender, point_fill = gender)) + geom_density_ridges( jittered_points = TRUE, # Critical for showing points (dev version feature) position = position_points_jitter(width = 0.4), # Control point spread alpha = 0.6, # Soften ridge transparency point_size = 2.5 # Adjust point size for visibility ) + # Assign shapes: Square (15) for Female, Triangle (17) for Non-Female scale_point_shape_manual(values = c("Female" = 15, "Non-Female" = 17)) + # Assign fill colors: Green for Female, Blue for Non-Female scale_point_fill_manual(values = c("Female" = "#27ae60", "Non-Female" = "#2980b9")) + labs(title = "Ridge Plot with Gender-Specific Points", x = "Metric Value", y = "Category", point_shape = "Gender", point_fill = "Gender") + theme_minimal()
Quick Tips:
- If you haven’t installed the dev version of ggridridges yet, run:
devtools::install_github("clauswilke/ggridridges") - Shapes like 15 (square) and 17 (triangle) are filled shapes—if you wanted unfilled outlines, use shapes like 0 (square) or 2 (triangle) and replace
point_fillwithpoint_color. - Tweak
position_points_jitter(width)to adjust how spread out the points appear along the x-axis.
内容的提问来源于stack exchange,提问作者Matti Heino
相关产品推荐
相关产品推荐

