【问题标题】:Multiple Fixed Lines for Text per Legend Label in ggplot2ggplot2中每个图例标签的多个固定文本行
【发布时间】:2020-06-24 16:26:09
【问题描述】:

(这个问题扩展了Multiple Lines for Text per Legend Label in ggplot2。)

我需要在图例标签中包含多行信息。这些标签需要在固定点分成几行,这就是前面示例中的解决方案对我不起作用的原因。我试过使用\n,但在我使用的表达式中,我最终得到了一个偏移量。

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)

我最终得到的是第三行偏离对齐的其余部分,并且图例没有正确间隔。

感谢您的帮助!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以在theme 中使用ggtext 和element_markdown(),这为您提供了很大的灵活性:

    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"))
    

    【讨论】:

      猜你喜欢
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 2022-01-20
      相关资源
      最近更新 更多