2016-09-22 133 views
1

Stagger axis labels, new feature in ggplot2在x轴标签追问:错开轴标签,新功能在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轴的值,但导航这种结构有点陌生。任何建议或意见或资源,以避免浪费时间猜测,不胜感激。

+0

@Sandy Muspratt可能对这个,所以我试图让他们通知输入。如果有更好的方法,请告诉我。 – Jas

+0

也许@spindoctor已经想出了如何做到这一点。 – Jas

回答

1

你只需要改变高度在这种情况下不是宽度。同样在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

+0

太棒了!我将g $ heights [4] = unit(1,“cm”)改为g $ heights [4] = unit(2.5,“cm”),效果很好!我也用y = unit(c(1,0),“npc”),## – Jas