r - 将文本背景设置为 ggplot 轴文本

标签 r ggplot2 gridextra gtable

我有一个 ggplot 图形,它有一个长文本作为 Y 轴。

我正在尝试找到一种方法来设置 Y 轴的背景颜色,并使用两种不同颜色的“斑马主题”,如下所示

element_text() 中似乎没有 ggplot 功能。

有人可以帮助我吗?

谢谢

特洛帕夏

最佳答案

如果你破解了主题系统,这可能是可能的,但这可能不是一个好主意。

enter image description here

library(grid)

element_custom <- function(...) {
  structure(list(...), class = c("element_custom", "element_blank"))
}

element_grob.element_custom <- function(element, label, x, y, ...)  {
  tg <- textGrob(label, y=y, gp=gpar(col=element$colour))
  padding <- unit(1,"line")
  rg <- rectGrob(y=y,width=grobWidth(tg)+padding, height=unit(1,"line")+padding, 
                 gp=gpar(fill = element$fill, col=NA, alpha=0.1))
  gTree(children=gList(rg, tg), width=grobWidth(tg) + padding, cl="custom_axis")
}

widthDetails.custom_axis <- function(x) x$width + unit(2,"mm") # fudge


qplot(1:3,1:3) +
  theme(axis.text.y = element_custom(colour = 1:2, fill=1:2))

关于r - 将文本背景设置为 ggplot 轴文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45956883/

相关文章:

r - 使用 grid_draw 方法而不是 gridExtra 保存绘图

r - 避免将 alpha 美学应用于 ggplot2 中的 geom_text

r - 使用 ggplot2 绘制 1000 行

r - 为因子内的 NA 值分配预定水平

r - 在 Rmarkdown 中动态创建选项卡对 ggplot 不起作用,而对 plotly 起作用

r - for循环中的多个图忽略par

r - 如何在 do.call 中添加函数的更多参数?

R - 如何在特定轮廓内找到点

r - 将持续时间拆分为年度部分

r - geom_raster() 没有填充和图例