首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ggplot2中更改x和y轴的位置

如何在ggplot2中更改x和y轴的位置
EN

Stack Overflow用户
提问于 2013-03-11 16:56:03
回答 2查看 23.9K关注 0票数 28

在我的实际研究中,在顶部(或顶部和底部)显示x轴和在右侧显示y轴是非常常见的。但是,在ggplot2中,默认位置是底部的x和左侧的y。

Kohske Post Here之后,使用的命令如下:

代码语言:javascript
复制
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"))

我已经在dev-mode中尝试过上面的命令:

代码语言:javascript
复制
install_packages("devtools")
library(devtools)
dev_mode()
install_github("ggplot2", "kohske", "feature/pguide")
library(ggplot2) 

不幸的是,它在最新的plyr包中不能很好地工作。消息:

代码语言:javascript
复制
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,消息是:

代码语言:javascript
复制
Error in continuous_scale(c("x", "xmin", "xmax", "xend", "xintercept"),  : 
  formal argument "guide" matched by multiple actual arguments

我注意到Hadley说这个功能在他的待办事项清单上。然而,目前我找不到解决方案。有人能帮上忙吗?

EN

回答 2

Stack Overflow用户

发布于 2016-11-16 01:41:32

ggplot 2.2.0中,您可以在scale_中使用position参数设置轴的位置

代码语言:javascript
复制
ggplot(mpg, aes(displ, hwy)) + 
  geom_point() + 
  scale_x_continuous(position = "top") + 
  scale_y_continuous(position = "right")

票数 15
EN

Stack Overflow用户

发布于 2013-03-11 17:43:48

ggplot2解决方案

我采用This solution来创建一个正确的y轴。就我个人而言,我发现在gtable中操纵grobs真的很难。我放弃了x轴,但我给出了一个格子解。我希望这个功能能尽快在ggplot2中实现。

代码语言:javascript
复制
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)

格子解

这不是ggplot2解决方案,而是lattice解决方案。使用带有ggplot2主题的latticeExtra,我们可以获得类似的外观和所需的行为。

代码语言:javascript
复制
library(latticeExtra)
xyplot(y~ x, type='l', scales=list(x=list(alternating=2),
                                   y=list(alternating=2)),
       par.settings = ggplot2like(),axis=axis.grid)

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15334494

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档