简体   繁体   English

在主题后添加自定义图例(legend.title=element_blank(), legend.position='none')

[英]Adding custom legend after theme(legend.title=element_blank(), legend.position='none')

I have the following data:我有以下数据:

set.seed(100)
vals <- rnorm(100)
groups <- c(rep('group a', 30), rep('group b', 70))
df <- data.frame('vals'=vals, 'groups'=groups)

I plot the distributions of vals within groups like this:我 plot 组内的 val 分布如下:

ggplot(df, aes(y=vals, x=groups, fill=groups)) +
geom_boxplot() +
theme_minimal() +
scale_fill_brewer(palette = "Set3") +
geom_hline(yintercept=0.5, color='red', lty='dashed', size=1) +
geom_hline(yintercept=-0.5, color='blue', lty='dashed', size=1) +
theme(legend.title=element_blank(), legend.position='none') 

This produces the following picture.这会产生下图。

在此处输入图像描述

I would like to include a legend for the blue and red horizontal lines but not for the boxplots.我想包括蓝色和红色水平线的图例,但不包括箱线图。 How do I do that?我怎么做?

You could use the aes of l.netype for each geom_hline with scale_l.netype_manual and say that the boxplot should not be shown like this:您可以将l.netypeaes用于每个geom_hlinescale_l.netype_manual并说箱线图不应该像这样显示:

set.seed(100)
vals <- rnorm(100)
groups <- c(rep('group a', 30), rep('group b', 70))
df <- data.frame('vals'=vals, 'groups'=groups)

library(ggplot2)
ggplot(df, aes(y=vals, x=groups, fill=groups)) +
  geom_boxplot(show.legend = FALSE) +
  theme_minimal() +
  scale_fill_brewer(palette = "Set3") +
  geom_hline(aes(yintercept=0.5, lty='red'), color='red', size=1) +
  geom_hline(aes(yintercept=-0.5, lty='blue'), color='blue', size=1) +
  scale_linetype_manual(name = "Legend", values = c(2, 2), 
                        guide = guide_legend(override.aes = list(color = c("red", "blue")))) 

Created on 2023-01-16 with reprex v2.0.2创建于 2023-01-16,使用reprex v2.0.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM