代码之家  ›  专栏  ›  技术社区  ›  Canovice

是否可以将具有边框半径的边框添加到x轴标题?

  •  1
  • Canovice  · 技术社区  · 3 年前
    library(ggplot2)
    
    data <- data.frame(x = c(1, 2, 3, 4, 5), y = c(5, 4, 3, 2, 1))
    ggplot(data, aes(x = x, y = y)) +
      geom_point() +
      labs(x = "X-Axis Title", y = "Y-Axis Title") +
      theme(axis.title.x = element_text(size = 12, color = "black", face = "bold", hjust = 0.5, vjust = -0.2, angle = 0))
    

    这是一个基本的 ggplot 具有X轴。我们正试图创建一个X轴,它看起来像:

    enter image description here

    这可能吗?

    2 回复  |  直到 3 年前
        1
  •  3
  •   Jon Spring    3 年前
      ... + 
    theme(axis.title.x = ggtext::element_textbox(linetype = 1, 
                                                 r = grid::unit(10, "pt"),
                                                 padding = margin(5, 10, 5, 10)))
    

    enter image description here

        2
  •  1
  •   jared_mamrot    3 年前

    另一个潜在的选择是使用电网 roundrectGrob :

    library(tidyverse)
    library(grid)
    
    element_custom <- function() {
      structure(list(), class = c("element_custom", "element_text"))
    }
    
    element_grob.element_custom <- function(element, label="", ...)  {
      tg <- textGrob(label)
      padding <- unit(1,"line")
      rg <- roundrectGrob(width=grobWidth(tg)+padding,
                          height=grobHeight(tg)+padding,
                          r = unit(0.75, "line"))
      gTree(children=gList(rg, tg), height=grobHeight(tg) + padding, cl="custom_axis")
    }
    
    heightDetails.custom_axis <- function(x) x$height + unit(2,"mm")
    
    data <- data.frame(x = c(1, 2, 3, 4, 5), y = c(5, 4, 3, 2, 1))
    
    ggplot(data, aes(x = x, y = y)) +
      geom_point() +
      labs(x = "X-Axis Title", y = "Y-Axis Title") +
      theme(axis.title.x = element_text(size = 12, color = "black", face = "bold", hjust = 0.5, vjust = -0.2, angle = 0)) +
      (theme_grey() %+replace% theme(axis.title.x = element_custom()))
    

    创建于2023-01-13 reprex v2.0.2

    或者,也许@Teunband在 elementalist package (值得一看)。

    推荐文章