跟进x轴标签:交错轴标签,ggplot2

时间:2016-09-22 23:24:28

标签: r plot ggplot2

Stagger axis labels, new feature in ggplot2

我是R的新人,并且@Sandy Muspratt对@spindoctor的回答有点令人生畏。答案适用于y轴标签。我尝试了一些编辑。例如我改变了:

index <- which(g$layout$name == "axis-l")  # Which grob

为:

index <- which(g$layout$name == "axis-b")  # Which grob

但是x轴标签保持不变,没有交错。您能否指出如何修改代码以使其适用于x轴标签?

# Get the grob
g <- ggplotGrob(out.plot)

# Get the y axis
index <- which(g$layout$name == "axis-l")  # Which grob
yaxis <- g$grobs[[index]]   

# Get the ticks (labels and marks)
ticks <- yaxis$children[[2]]

# Get the labels
ticksL <- ticks$grobs[[1]]

# Make the edit
ticksL$children[[1]]$x <- rep(unit.c(unit(c(1,0,-1),"npc")), 27)

# Put the edited labels back into the plot
ticks$grobs[[1]] <- ticksL
yaxis$children[[2]] <- ticks
g$grobs[[index]] <- yaxis

# Make the relevant column a little wider
g$widths[3] <- unit(2.5, "cm")

# Draw the plot
grid.newpage()
grid.draw(g)

TableGrob的输出如下:

>g
TableGrob (6 x 5) "layout": 8 grobs
  z     cells       name                                   grob
1 0 (1-6,1-5) background        rect[plot.background..rect.507]
2 3 (3-3,3-3)     axis-l    absoluteGrob[GRID.absoluteGrob.498]
3 1 (4-4,3-3)     spacer                         zeroGrob[NULL]
4 2 (3-3,4-4)      panel                  gTree[GRID.gTree.484]
5 4 (4-4,4-4)     axis-b    absoluteGrob[GRID.absoluteGrob.491]
6 5 (5-5,4-4)       xlab titleGrob[axis.title.x..titleGrob.501]
7 6 (3-3,2-2)       ylab titleGrob[axis.title.y..titleGrob.504]
8 7 (2-2,4-4)      title     zeroGrob[plot.title..zeroGrob.505]

我尝试识别相关的x,y轴值,但导航这个结构对我来说有点陌生。任何建议或评论或资源,以避免时间浪费猜测非常感谢。

1 个答案:

答案 0 :(得分:2)

在这种情况下,您只需更改高度而不是宽度。同样在editGrob中,您需要传递y广告位而不是x,因为您正在更改坐标,而y轴在x上不是从左到右。

我保持一切相同但注释掉了我改变的内容并将我的更改直接放在了下面。

# Libraries
library(ggplot2)
library(gtable)
library(grid)
library(stringi)

# fake data
set.seed(12345)
var <- stri_rand_strings(81, 4, pattern = '[HrhEgeIdiFtf]')
var1 <- rnorm(81, mean = 175, sd = 75)
out <- data.frame(var, var1)
out$var <- factor(out$var, levels = out$var[order(out$var1, decreasing = FALSE)])

# Plot
# out.plot <- ggplot(out, aes(x = var, y = var1)) + geom_point() + coord_flip()
out.plot <- ggplot(out, aes(x = var1, y = var)) + geom_point() + coord_flip()

# Get the ggplot grob
g = ggplotGrob(out.plot)

# Get a hierarchical list of component grobs
grid.ls(grid.force(g))

# make the relevant column a little wider
# g$widths[3] = unit(2.5, "cm")
g$heights[4] = unit(1, "cm")

# The edit
g = editGrob(grid.force(g),
             gPath("axis-b", "axis", "axis", "GRID.text"),
             # x = unit(c(-1, 0, 1), "npc"), 
             y = unit(c(1, 0, -1), "npc"), ## or c(-1,0,1) etc to change order
             grep = TRUE)

# Draw the plot
grid.newpage()
grid.draw(g)

enter image description here