在ggplot2中画线

Rea*_*onk 5 r ggplot2

我有一个情节,我想从画线(0,0)(15,15),与传奇.我如何实现这一目标?情节:

frame <- read.table('pastie_from_web', sep=",", header=TRUE)
colnames(frame) <- c("pos", "word.length")
plot <- ggplot(frame, aes(x=pos, y=word.length)) + scale_x_continuous(limits=c(1,15)) + scale_y_continuous(limits=c(1,15))+ geom_density2d(aes(color=..level..)) + scale_color_gradient(low="black", high="red") + opts(legend.position="none")
png(paste("graphs/", fname, ".png", sep=""), width=600, height=600)
print(plot)
Run Code Online (Sandbox Code Playgroud)

数据:http://sprunge.us/gKiL

structure(list(position = c(2, 2, 2, 2, 7, 8, 4, 5, 4, 9, 5, 
2, 7, 9, 9, 6, 5, 6, 9, 2, 6, 5, 5, 7, 7, 5, 6, 5, 5, 3, 2, 4, 
5, 2, 3, 2, 7, 5, 2, 5, 2, 6, 8, 7, 2, 8, 5, 4, 2, 5, 2, 2, 2, 
6, 8, 2, 2, 9, 5, 2, 4, 7, 3, 4, 9, 5, 5, 5, 5, 4, 7, 2, 7, 2, 
4, 4, 3, 2, 5, 6, 5, 5, 5, 5, 4, 4, 8, 7, 5, 7, 4, 3, 4, 5, 2, 
6, 6, 4, 4, 2, 2, 3, 2, 2, 6, 2), word.length = c(5L, 5L, 6L, 
4L, 9L, 11L, 5L, 8L, 8L, 10L, 8L, 9L, 8L, 10L, 10L, 7L, 9L, 10L, 
11L, 10L, 10L, 8L, 13L, 11L, 11L, 13L, 7L, 9L, 6L, 4L, 9L, 8L, 
9L, 6L, 4L, 5L, 11L, 13L, 13L, 13L, 10L, 9L, 11L, 8L, 4L, 10L, 
8L, 16L, 3L, 5L, 4L, 12L, 12L, 15L, 9L, 12L, 12L, 11L, 11L, 8L, 
16L, 9L, 8L, 7L, 10L, 11L, 6L, 13L, 5L, 8L, 8L, 5L, 8L, 5L, 6L, 
6L, 7L, 10L, 13L, 7L, 6L, 13L, 9L, 6L, 7L, 8L, 11L, 8L, 8L, 8L, 
8L, 8L, 7L, 6L, 5L, 9L, 9L, 5L, 5L, 6L, 7L, 8L, 8L, 10L, 8L, 
10L)), .Names = c("position", "word.length"), class = "data.frame", row.names = c(NA, 
-106L))
Run Code Online (Sandbox Code Playgroud)

Rei*_*son 6

以下是一个示例数据集来说明:

set.seed(42)
dat <- data.frame(x = runif(20, min = 0, max = 20),
                  y = runif(20, min = 0, max = 20))

p <- ggplot(dat, aes(x = x, y = y)) 
p + geom_point() + 
    geom_line(data = data.frame(x = c(0,15), y = c(0,15)),
              aes = aes(x = x, y = y), colour = "red")
Run Code Online (Sandbox Code Playgroud)

注意我们如何data为geoms 指定不同的参数,这允许我们在原始ggplot()调用中定义的相同绘图区域上绘制不同的数据对象.注意:如果第二个数据框(在geom_line()调用中)具有与原始图相同的x和y轴映射,那么您不需要新的,aes()因为我最初拥有代码(请参阅答案的修订历史记录).这可能不是很清楚,@Justin的评论促使我改变了geom_line()包含一个新的aes()调用来将数据映射到美学; 在我的例子中不需要它,但在现实世界中可能需要它.

以上给出:

在此输入图像描述

如果您想要不同的任意线,请考虑geom_abline()使用给出斜率和截距来绘制线条.geom_segment()是上面geom_line()指定开始和结束x和y坐标的替代方法.请参阅geoms的相应帮助页面以确定您更喜欢使用哪个.

  • 你没有为`geom_line`提供一个新的'aes(...)`,所以它试图使用第一个`ggplot`中定义的那个.而是在Gavin的答案中添加适当的`aes`或更改`geom_line` data.frame的名称以匹配. (2认同)