如何在ggplot facet wrap标签中使用不同的字体大小?

时间:2016-03-31 13:10:50

标签: r ggplot2 facet

我想在facet wrap的标签中创建两种不同大小的文本。

例如:

  • 物种X(大小14)
  • 总捕获量(n = 133)(大小12)

test <- read.csv(paste0(path, "Costello Artvgl2 for Stack.csv"), sep = ";", dec = ",", header = T)

str(test)


test$Wert <- factor(test$Wert, levels = c("one","two","three","four","five","six")) 


test$Sampling.site <- factor(test$Sampling.site, levels = c("Species X Area T","Species Y Area T","Species X Area A","Species Y Area B","Species X Area B","Species Y Area C"))


levels(test$Sampling.site) <-  c("Species X\nTotal catch (n=133)", "Species Y\nTotal catch (n=185)", "Species X\nSampling area A (n=57)", "Species Y\nSampling area B (n=122)",
                             "Species X\nSampling area B (n=76)",  "Species Y\nSampling area C (n=63)")

theme_new <- function(base_size = 12, base_family = base_family){
theme_bw(base_size = base_size) %+replace%
theme(
  axis.text.x =       element_text(size = 8 ),
  axis.text.y =       element_text(size = 8 ),
  axis.title.x =        element_text(size = 12, vjust = 0.01),
  axis.title.y =        element_text(size = 12, vjust = 0.9, angle = 90),

  plot.title =        element_text(size = 10, face = "bold"),

  legend.key=         element_rect(colour= NA, fill =NA, size = 0.5),
  legend.key.size =   unit(1, "lines"),
  legend.text =       element_text(size = 8),
  legend.title =      element_blank(),

  strip.background =  element_rect(fill = NA, colour = NA), 
  strip.text =        element_text(size = 8, face = "bold",hjust = 0.5, vjust = 0.9),

  panel.background =  element_rect(fill = "white"), 
  panel.border =      element_rect(fill = NA, colour="black"), 
  panel.grid.major =  element_blank(),
  panel.grid.minor =  element_blank(),
  panel.margin =      unit(1, "lines")

)
}

ggplot(test, aes(Fi, Pi),group=Wert)+
geom_point(aes(colour = factor(Wert),shape = factor(Wert)),size=3)      +                         
  scale_shape_manual(values=c(20,18,19,15,16,17))+                    
  scale_x_continuous(limits=c(0, 1),breaks=c(0,0.2,0.4,0.6,0.8,1.0))+     
  scale_colour_brewer(type = "qual", palette = "Paired")+
  scale_y_continuous(limits=c(0, 100),breaks=c(0,20,40,60,80,100))+        
  labs(x = "Frequency of occurrence", y = "Prey-specific abundance [%]")+ 
  facet_wrap(~Sampling.site,scales = "free",ncol = 2) +
  theme_new()

是否有可能意识到这一点?

2 个答案:

答案 0 :(得分:8)

下面的解决方案是一个黑客,因为它使用上标(或下标)来获得facet标签第二行的较小字体大小。我不确定如何更好地控制标签尺寸而不需要直接操纵条带凹凸,尽管可能有办法编写labeller函数来执行此操作。

我们将使用内置的mtcars数据框作为示例。首先,我们将添加将用于刻面和标注的列。我们将面向cyl,但我们希望标签的第一行显示该方面的柱面数,第二行显示该方面中的数据点数。为此,我们将在mtcars中创建两个新列,称为Label1Label2,我们将使用它们来创建构面标签的每一行。我们将通过这两列来获取图表中我们想要的标签。 (Label3类似于Label2,但使用下标而不是上标;这只有在您想要更改从第二行底部到绘图面板顶部的距离时才有意义。)

Label1Label2是文本字符串,但它们以表达式的形式存在,因此我们可以在创建绘图时使用label_parsed来获取较小的下标文本。

library(ggplot2)
library(dplyr)
library(grid)

mtcars.new = mtcars %>% group_by(cyl) %>% 
  summarise(Label1=paste0("bold(Cylinders:~", unique(cyl),")"),
            Label2=paste0("bold(NULL[Count:~", length(cyl),"])"),
            Label3=paste0("bold(NULL^{Count:~", length(cyl),"})")) %>%
  full_join(mtcars)

现在我们可以创建情节了。 Label1Label2的分面为我们提供了两条线。因为我们为Label2创建了一个下标表达式,所以当我们使用label_parsed标注构面时,会以较小的字体呈现。相对于Label2,我更喜欢Label1稍大一点,但是这种(hacky)方法无法控制它。此外,虽然element_text有一个lineheight参数,但ggplot似乎并不尊重它。因此,我手动重置条带标签的线高,以减少两个标签之间的空间。

p = ggplot(mtcars.new, aes(wt, mpg)) +
  geom_point() +
  facet_grid(. ~ Label1 + Label2, labeller=label_parsed) +
  theme_bw() +
  theme(strip.background=element_rect(fill=NA, color=NA),
        strip.text=element_text(size=12))

g <- ggplotGrob(p)
g$heights[[3]] = unit(0.5,"lines")

grid.draw(g)

enter image description here

答案 1 :(得分:3)

当前正在开发的ggtext软件包为该问题提供了更优雅的解决方案。它支持一小组HTML标记,可用于设置文本标签的各个部分的样式。

注意:安装ggtext的开发版本可能会拉入ggplot2的开发版本。

library(tidyverse)
library(ggtext) # remotes::install_github("clauswilke/ggtext")
library(glue)
#> 
#> Attaching package: 'glue'
#> The following object is masked from 'package:dplyr':
#> 
#>     collapse

count(mtcars, cyl)  %>% 
  mutate(
    cyl_lab = as.character(
      glue("Cylinders: {cyl}<br><span style='font-size:9pt'>Count: {n}</span>")
    )
  ) %>%
  full_join(mtcars) %>%
  ggplot(aes(wt, mpg)) +
  geom_point() +
  facet_grid(. ~ cyl_lab) +
  theme_bw(12) +
  theme(strip.background=element_rect(fill=NA, color=NA),
        strip.text=element_markdown(size = 12, lineheight = 1.1))
#> Joining, by = "cyl"

reprex package(v0.3.0)于2020-01-07创建