简体   繁体   中英

Multiple Fixed Lines for Text per Legend Label in ggplot2

(This question expands on Multiple Lines for Text per Legend Label in ggplot2 .)

I need to include multiple lines of information in legend labels. These labels need to be broken into lines at fixes points, which is why the solution in the previous example doesn't work for me. I've tried using \n , but in the expression I'm using, I end up with an offset.

set.seed(10)
dat_sof<-tibble(x=seq(1:10))%>%
            mutate(y=x+rnorm(10))

leg_col<-c("S1"="blue", "S2"='black')
leg_lty<-c("S1"=1, "S2"=2)
leg_lab<-c(expression("S1:\n y = m1 x + b1\n"~ R^{2} ~ " = r1, n = n1"), 
           expression("S2:\n y = m2 x + b2\n"~ R^{2} ~ " = r2, n = n2"))

ggplot(data=dat_sof, aes(x=x, y=y))+
  geom_point()+
  geom_smooth(method='lm', aes(color="S1", lty="S1"), se=F)+
  geom_abline(aes(color="S2", lty="S2", slope=1, intercept=0.1))+
  theme_bw(base_size=14)+
  scale_color_manual(values=leg_col, name="Regressions", labels=leg_lab)+
  scale_linetype_manual(values=leg_lty, name="Regressions", labels=leg_lab)+
  theme(legend.text.align = 0)

What I end up with is the third line being off-set from the rest of the alignment, and the legend not being properly spaced. 完全不可读的传说

Thank you for your help!

You can use ggtext and use element_markdown() in your theme which gives you a lot of flexibility:

library(ggplot2)
library(dplyr)
set.seed(10)
dat_sof<-tibble(x=seq(1:10))%>%
  mutate(y=x+rnorm(10))

leg_col<-c("S1"="blue", "S2"='black')
leg_lty<-c("S1"=1, "S2"=2)
leg_lab <- c("S1:<br>y = m1x + b1<br>R<sup>2</sup> = r1, n = n1",
             "S1:<br>y = m2x + b2<br>R<sup>2</sup> = r2, n = n2")
ggplot(data=dat_sof, aes(x=x, y=y))+
  geom_point()+
  geom_smooth(method='lm', aes(color="S1", lty="S1"), se=F)+
  geom_abline(aes(color="S2", lty="S2", slope=1, intercept=0.1))+
  theme_bw(base_size=14)+
  scale_color_manual(values=leg_col, name="Regressions", labels=leg_lab)+
  scale_linetype_manual(values=leg_lty, name="Regressions", labels=leg_lab)+
  theme(legend.text.align = 0,
        legend.text = ggtext::element_markdown(),
        legend.key.height=unit(2, "cm"))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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