用R中的ggplot2绘制双色轴

时间:2014-09-25 11:38:57

标签: r plot ggplot2

我试图模仿,例如ggplot2中的以下基本图形(用于构建校准的双色轴):

## Base graphics
plot(-1:1, -1:1, asp = 1, type = "n", xaxt = "n", yaxt = "n", xlab = "", ylab = "")
abline(a = 0, b = -0.75)
abline(a = 0, b = 0.25)
abline(a = 0, b = 2)
mtext("V1", side = 4, at = -0.75*par("usr")[2])
mtext("V2", side = 2, at = 0.25*par("usr")[1])
mtext("V3", side = 3, at = par("usr")[4]/2)

对mtext()的调用将变量名称添加到绘图边距并指示各个轴的正方向。

但是,似乎没有ggplot2等同于基本图形的mtext()函数。因此,我无法弄清楚如何将变量名称放在图的边缘。有没有人有关于如何做到这一点的想法?

最好我不想禁用剪辑。以下是上述ggplot2版本的一些等效代码:

## ggplot2 attempt
library(ggplot2)
df <- data.frame(x = -1:1, y = -1:1)
dfLabs <- data.frame(x = c(1, -1, 1/2), y = c(-0.75, -0.25, 1), labels = paste0("V", 1:3))
p <- ggplot(data = df, aes(x = x, y = y)) +  geom_blank() + 
   geom_abline(intercept = rep(0, 3), slope = c(-0.75, 0.25, 2)) +
   theme_bw() + coord_cartesian(xlim = c(-1, 1), ylim = c(-1, 1)) +
   theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks =   element_blank(),
   panel.grid = element_blank())
p + geom_text(data = dfLabs, mapping = aes(label = labels)) 

必须修改最后一行中的geom_text()调用。

0 个答案:

没有答案