r - 在 ggplot (R) 上显示两个平行轴

标签 r plot ggplot2 axis-labels

假设我们有以下类型的简单图。

library(ggplot2)
df = data.frame(y=c(0,1.1,2.3,3.1,2.9,5.8,6,7.4,8.2,9.1),x=seq(1,100, length.out=10))
ggplot(df,aes(x=x,y=y)) + geom_point()

xz 完美关联。关系是:Constant=x^2*z=1.23 因此我可以像这样重写 data.frame:

df = cbind(df,1.23/df$x^2)

问题是:

如何在 x 轴上同时显示变量 xz 一个在底部,一个在底部图表顶部或底部。

最佳答案

这是一次危险的尝试。具有对数刻度的先前版本只是错误

library(ggplot2)
df = data.frame(y=c(0,1.1,2.3,3.1,2.9,5.8,6,7.4,8.2,9.1),
                x=seq(1,100, length.out=10))
df$z = 1.23/df$x^2


## let's at least remove the gridlines
p1 <- ggplot(df,aes(x=x,y=y)) + geom_point() +
  scale_x_continuous(expand=c(0,0)) +
  theme(panel.grid.major=element_blank(),
        panel.grid.minor = element_blank())

## make sure both plots have expand = c(0,0) 
## otherwise data and top-axis won't necessarily be aligned...
p2 <- ggplot(df,aes(x=z,y=y)) + geom_point() +
  scale_x_continuous(expand=c(0,0))

library(gtable)
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
tmp <- gtable_filter(g2, pattern="axis-b")

## ugly tricks to extract and reshape the axis
axis <- tmp[["grobs"]][[1]][["children"]][["axis"]] # corrupt the children
axis$layout <- axis$layout[2:1,]
axis$grobs[[1]][["y"]] <- axis$grobs[[1]][["y"]] - unit(1,"npc") + unit(0.15,"cm")
## back to "normality"    

g1 <- gtable_add_rows(g1, sum(tmp$heights), 2)
gtableAddGrobs <- gtable_add_grob # alias, making sure @!hadley doesn't see this
g1 <- gtableAddGrobs(g1, 
                     grobs=list(gtable_filter(g2, pattern="xlab"),axis), 
                     t=c(1,3), l=4)
grid.newpage()
grid.draw(g1)

enter image description here

关于r - 在 ggplot (R) 上显示两个平行轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18509723/

相关文章:

r - 用R中的数据点名称制作一维图

r - 带有 ggvis : how to plot multiple groups with different shape markers and corresponding fitted regression lines 的 R 中的散点图

python - plt.bar 错误,类型错误 : bar() missing 1 required positional argument: 'height'

python-3.x - 如何使用 basemap Python 在背景之上绘制散点图

r - 如何在小平面网格线之间放置分隔线

r - 误差线未在条形图上正确绘制

在 gganimate 中将动画 barplot 条上的标签舍入?

r - 将未计算的命令传递给 R 中的函数

r - 使用按钮扩展保留 Excel 中的数字格式

python - Pandas groupby plot 给出了第一个 plot 两次