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

在ggplot2中修改图例名称且不改变theme_gray主题颜色

Solution to Keep Default theme_gray Colors & Customize Legend/Label Names

Got it, let's sort this out for you! The issue with your original code is that the labels argument inside labs() doesn't modify the category labels in your legend—it's meant for axis labels instead. To keep the default theme_gray() color palette while setting custom legend titles and category labels, here's what you need to do:

Step-by-Step Breakdown

  1. Retain default colors: Skip manually specifying color values (like values = c("#xxx", "#xxx"))—this ensures you stick with theme_gray()'s built-in discrete color scheme.
  2. Customize legend category labels: Use scale_color_discrete(labels = ...) to map your original column names to the friendly labels you want ("Actual", "Simulation").
  3. Set legend title: Use labs(color = "Legend") to define the title at the top of your legend, along with your axis labels as before.

Modified Working Code

library(tidyverse)

data1 %>% 
  gather(key, value) %>% 
  ggplot(aes(value, color = key)) +
  stat_ecdf(size = 0.8) +
  xlim(-4.5, 4.5) +
  # Map original column names to your custom labels (adjust order if needed)
  scale_color_discrete(labels = c("Actual", "Simulation")) +
  # Set legend title and axis labels
  labs(x = "t(α)", y = "Probability", color = "Legend")

Pro Tip for Reliability

If you're worried about label order matching your original columns (in case data1's columns aren't in the exact order you expect), use a named vector to explicitly map each original column name to its custom label:

scale_color_discrete(labels = c("original_col1_name" = "Actual", "original_col2_name" = "Simulation"))

This way, you don't have to rely on column order, and your labels will always align correctly with the right data series—all while keeping that default theme_gray() color palette you want.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:09:50