You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 setting color='orange' outside the aesthetic, we assign descriptive labels (like "Empirical Data") to the color parameter inside aes(). This tells ggplot to create a legend entry for each label.
  • Single Legend Entry for Models: By mapping color to 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 alpha parameter keeps model lines transparent, and linewidth makes the empirical line pop against the simulations.

Quick Adjustments You Might Want:

  • Tweak alpha values (0 = fully transparent, 1 = opaque) to balance how prominent the model lines are.
  • Change the name in scale_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_density line with:
    geom_density(aes(x = empirical_data, color = "Empirical Data"), linewidth = 1)
    

内容的提问来源于stack exchange,提问作者Jeremy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:47:45