在ggplot2中修改图例名称且不改变theme_gray主题颜色
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
- Retain default colors: Skip manually specifying color values (like
values = c("#xxx", "#xxx"))—this ensures you stick withtheme_gray()'s built-in discrete color scheme. - Customize legend category labels: Use
scale_color_discrete(labels = ...)to map your original column names to the friendly labels you want ("Actual", "Simulation"). - 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

