Home > Software design >  Is it possible to add border with border radius to x-axis title?
Is it possible to add border with border radius to x-axis title?

Time:01-13

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

Here is a basic ggplot with an X-Axis. We are attempting to create an X-Axis that looks something like:

enter image description here

Is this possible?

CodePudding user response:

  ...   
theme(axis.title.x = ggtext::element_textbox(linetype = 1, 
                                             r = grid::unit(10, "pt"),
                                             padding = margin(5, 10, 5, 10)))

enter image description here

CodePudding user response:

Another potential option is to use grid's 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()))

Created on 2023-01-13 with reprex v2.0.2

Or, perhaps @Teunbrand has a function in the elementalist package (worth a look).

  • Related