ggplot叠加密度图的图例配置技术咨询
Fixing the Legend for Your Density Overlay Plot
I get it—you’ve got your overlay looking exactly how you want, but the legend is missing because we need to tie our color labels to the aes() aesthetic instead of setting them directly outside of it. Here’s how to adjust your code to add a clear, functional legend:
Step-by-Step Corrected Code
library(ggplot2) # Generate your simulation data (fixed to ensure 100 models with 100 values each) model <- rep(1:100, each = 100) values <- rnbinom(10000, 1, .4) df <- data.frame(model, values) # Generate empirical data empirical_data <- rnbinom(1000, 1, .3) empirical_df <- data.frame(values = empirical_data) # Optional but cleaner structure # Build the plot with legend ggplot() + # Model simulations: map color to a label inside aes() for legend entry geom_line(stat = 'density', data = df, aes(x = values, group = model, color = "Model Simulations"), alpha = 0.2) + # Low opacity for model lines # Empirical data: map color to a label inside aes() geom_density(data = empirical_df, aes(x = values, color = "Empirical Data"), linewidth = 1) # Thicker line to stand out # Define custom colors and legend title scale_color_manual(name = "Dataset", values = c("Model Simulations" = "darkgray", "Empirical Data" = "orange")) + # Optional theme tweaks for readability theme_minimal() + labs(x = "Value", y = "Density")
Key Changes Explained:
- Map Colors in
aes(): Instead of settingcolor='orange'outside the aesthetic, we assign descriptive labels (like"Empirical Data") to thecolorparameter insideaes(). This tells ggplot to create a legend entry for each label. - Single Legend Entry for Models: By mapping
colorto a fixed label for all model lines, ggplot groups them under one legend item instead of creating 100 separate entries. - Custom Color Scale:
scale_color_manual()lets you explicitly set colors for each legend entry, so your model lines stay faint and uniform while the empirical line stays your desired orange. - Visibility Tweaks: The
alphaparameter keeps model lines transparent, andlinewidthmakes the empirical line pop against the simulations.
Quick Adjustments You Might Want:
- Tweak
alphavalues (0 = fully transparent, 1 = opaque) to balance how prominent the model lines are. - Change the
nameinscale_color_manual()to a legend title that fits your specific use case. - If you prefer to keep the empirical data as a vector instead of a data frame, replace the empirical
geom_densityline with:geom_density(aes(x = empirical_data, color = "Empirical Data"), linewidth = 1)
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

