2013-03-11 102 views
23

在我真正的研究的世界,这是很常见的,显示在顶部(或顶部和底部)在右边,y轴X轴。但是,默认位置在ggplot2的底部是x,左边是y。如何改变x和y轴的位置在GGPLOT2

Kohske Post Here,使用的命令是:

x <- seq(0, 10, 0.1) 
y <- sin(x * pi) 
qplot(x, y, geom = "line") + 
scale_x_continuous(guide = guide_axis(position = "top")) + 
scale_y_continuous(guide = guide_axis(position = "right")) 

我已经在上面开发模式命令尝试:

install_packages("devtools") 
library(devtools) 
dev_mode() 
install_github("ggplot2", "kohske", "feature/pguide") 
library(ggplot2) 

不幸的是,它没有很好地与最新plyr包工作。消息:

The following 'from' values not present in 'x': col, color, pch, cex, lty, lwd, srt, adj, bg, fg, min, max... 
Error in plyr:::split_indices(seq_len(nrow(data)), scale_id, n) 

然后我尝试了codes from github directedly,该消息是:

Error in continuous_scale(c("x", "xmin", "xmax", "xend", "xintercept"), : 
    formal argument "guide" matched by multiple actual arguments 

我注意到,哈德利说这个功能是他的待办事项清单上。但是,此刻我找不到解决方案。谁能帮忙?

回答

8

GGPLOT2解决方案

我采取This solution创建一个正确的Y轴。就我个人而言,我发现在gtable中使用grobs非常困难。我放弃了X轴,但我给了一个晶格解决方案。我希望这个功能将尽快在ggplot2中实现。

library(ggplot2) 
library(gtable) 
library(grid) 
grid.newpage() 
dat <- data.frame(x<-seq(0, 10, 0.1),y = sin(x * pi)) 
p <- ggplot(dat, aes(x, y)) + geom_line(colour = "blue") + theme_bw() 
# extract gtable 
g <- ggplot_gtable(ggplot_build(p)) 

# axis tweaks 
ia <- which(g$layout$name == "axis-l") 
ax <- g$grobs[[ia]]$children[[2]] 
ax$widths <- rev(ax$widths) 
ax$grobs <- rev(ax$grobs) 
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm") 
pp <- c(subset(g$layout, name == "panel", select = t:r)) 
g <- gtable_add_cols(g, g$widths[g$layout[ia, ]$l], length(g$widths) - 1) 
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b) 
g$grobs[[ia]]$children[[2]] <- NULL 
############################## 
ia <- which(g$layout$name == "ylab") 
ylab <- g$grobs[[ia]] 
g <- gtable_add_cols(g, g$widths[g$layout[ia, ]$l], length(g$widths) - 1) 
g <- gtable_add_grob(g, ylab, pp$t, length(g$widths) - 1, pp$b) 
g$grobs[[ia]]$label = '' 
grid.draw(g) 

enter image description here

晶格溶液

这不是一个GGPLOT2解决方案,但lattice之一。使用latticeExtra与ggplot2主题,我们可以得到与所需行为类似的外观。

library(latticeExtra) 
xyplot(y~ x, type='l', scales=list(x=list(alternating=2), 
            y=list(alternating=2)), 
     par.settings = ggplot2like(),axis=axis.grid) 

enter image description here

+4

“我希望这个功能将在GGPLOT2实施尽快“ - 不能同意更多。我也认为gtable方法的使用是相当困难的。此外,有没有办法使用“视口”方法(而不是grid.draw)来安排几个右y轴的情节? – bearcat 2013-03-12 03:14:41

+0

@bearcat要安排几个图,最好使用类似'library(gridExtra); grid.arrange(g,g)'的东西。但是尝试使用'Lattice'包,肯定会有一个学习曲线,但它是一个很好的包并且有很好的文档记录。 – agstudy 2013-03-12 04:40:22

+0

我相信“视口”方法对于特定用途具有更好的性能 - 例如,在尝试布置重叠子图时。对不起,我只是在等待更清晰易用的解决方案。 – bearcat 2013-03-13 07:35:16

8

ggplot 2.2.0可以设置与position说法轴的scale_位置:

ggplot(mpg, aes(displ, hwy)) + 
    geom_point() + 
    scale_x_continuous(position = "top") + 
    scale_y_continuous(position = "right") 

enter image description here

相关问题