简体   繁体   English

在 R 中使用 ggplot2 向二维密度图添加一条线

[英]Add a line to a 2D density plot using ggplot2 in R

Here is 2D density plot from Hadley Wickham's book:这是 Hadley Wickham 书中的 2D 密度图:

f2d <- with(faithful, MASS::kde2d(eruptions, waiting, 
                                  h = c(1, 10), n = 50))
df <- with(f2d, cbind(expand.grid(x, y), as.vector(z)))
names(df) <- c("eruptions", "waiting", "density")
erupt <- ggplot(df, aes(waiting, eruptions, fill = density)) +
   geom_tile() +
   scale_x_continuous(expand = c(0, 0)) + 
   scale_y_continuous(expand = c(0, 0))
erupt + scale_fill_gradient(limits = c(0, 0.04), low = "white", high = "black") 

在此处输入图片说明

I try to plot a line on top of this:我尝试在此之上绘制一条线:

mydf <- data.frame(x=c(50,60,70),y=c(2,3,4))
erupt + scale_fill_gradient(limits = c(0, 0.04), low = "white", high = "black") + geom_line(aes(x=x,y=x), data = mydf)

But I get the following error:但我收到以下错误:

Error in data.frame(x = c(50, 60, 70), y = c(50, 60, 70), fill = function (x,  : 
  arguments imply differing number of rows: 3, 0

I don't understand why this is.我不明白这是为什么。 Thank you.谢谢你。

Two problems, first as @aosmith says you need to set density specific to the aesthetic in geom_tile.两个问题,首先是@aosmith 所说的,您需要在 geom_tile 中设置特定于美学的密度。 secondly there's a typo in geom_line(aes(x=x,y=x)其次, geom_line(aes(x=x,y=x)有一个错字

So所以

erupt <- ggplot(df, aes(waiting, eruptions)) +
  geom_tile(aes(fill=density)) +
  scale_x_continuous(expand = c(0, 0)) + 
  scale_y_continuous(expand = c(0, 0))

mydf <- data.frame(x=c(50,60,70),y=c(2,3,4))
erupt + scale_fill_gradient(limits = c(0, 0.04), low = "white", high = "black") + 
  geom_line(aes(x=x,y=y), data = mydf)

Produces生产

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM