Highlighting individual axis labels in bold using ggplot2

后端 未结 3 2010
无人共我
无人共我 2020-12-31 10:58

I want to highlight individual axis labels in bold. I am aware of this answer by @MrFlick but I can\'t figure out how to do this a) for more than one item,

相关标签:
3条回答
  • 2020-12-31 11:46

    I'm not sure if you can map label characteristics by name, but it's definitely possible to do it by position with a call to theme:

    ggplot(xx, aes(x=CLONE, y=VALUE, fill=YEAR)) + 
      geom_bar(stat="identity", position="dodge") +
      facet_wrap(~TREAT) +
      theme(axis.text.x = element_text(face = c('bold', 'bold', 'plain', 'plain', 'bold')))
    

    Note that the listed font faces for axis.text.x are the same length as the labels of your x-axis (five elements). This produces:

    0 讨论(0)
  • 2020-12-31 11:49

    Here's a generic method to create the emboldening vector:

    colorado <- function(src, boulder) {
      if (!is.factor(src)) src <- factor(src)                   # make sure it's a factor
      src_levels <- levels(src)                                 # retrieve the levels in their order
      brave <- boulder %in% src_levels                          # make sure everything we want to make bold is actually in the factor levels
      if (all(brave)) {                                         # if so
        b_pos <- purrr::map_int(boulder, ~which(.==src_levels)) # then find out where they are
        b_vec <- rep("plain", length(src_levels))               # make'm all plain first
        b_vec[b_pos] <- "bold"                                  # make our targets bold
        b_vec                                                   # return the new vector
      } else {
        stop("All elements of 'boulder' must be in src")
      }
    }
    
    ggplot(xx, aes(x=CLONE, y=VALUE, fill=YEAR)) + 
      geom_bar(stat="identity", position="dodge") +
      facet_wrap(~TREAT) +
      theme(axis.text.x=element_text(face=colorado(xx$CLONE, c("A", "B", "E"))))
    
    0 讨论(0)
  • 2020-12-31 11:50

    You can create a named vector of expressions (that turn text to bold) in scale_x_discrete and use parse=TRUE to evaluate the expressions:

    ggplot(xx, aes(x=CLONE, y=VALUE, fill=YEAR)) + 
        geom_bar(stat="identity", position="dodge") +
        facet_wrap(~TREAT) +
        scale_x_discrete(labels=c("A"=expression(bold(A)), "C"=expression(bold(C)),
                                  "E"=expression(bold(E)), parse=TRUE))
    

    You can probably create the vector of expressions programmatically, rather than typing it out, but the way to do that is escaping me right now.

    0 讨论(0)
提交回复
热议问题