[英]A ggplot2 equivalent of the lines() function in basic plot
由于我不会涉及的原因,我需要在空白ggplot2图上绘制垂直法线曲线。 以下代码将其作为一系列带有x,y坐标的点完成
dfBlank <- data.frame()
g <- ggplot(dfBlank) + xlim(0.58,1) + ylim(-0.2,113.2)
hdiLo <- 31.88
hdiHi <- 73.43
yComb <- seq(hdiLo, hdiHi, length = 75)
xVals <- 0.79 - (0.06*dnorm(yComb, 52.65, 10.67))/0.05
dfVertCurve <- data.frame(x = xVals, y = yComb)
g + geom_point(data = dfVertCurve, aes(x = x, y = y), size = 0.01)
曲线清晰可辨但是一系列要点。 基本图中的lines()
函数会将这些点转换为平滑线。
是否有ggplot2等价物?
我看到了两种不同的方法。
第一个使用geom_segment
将每个点与下一个点“链接”起来。
hdiLo <- 31.88
hdiHi <- 73.43
yComb <- seq(hdiLo, hdiHi, length = 75)
xVals <- 0.79 - (0.06*dnorm(yComb, 52.65, 10.67))/0.05
dfVertCurve <- data.frame(x = xVals, y = yComb)
library(ggplot2)
ggplot() +
xlim(0.58, 1) +
ylim(-0.2, 113.2) +
geom_segment(data = dfVertCurve, aes(x = x, xend = dplyr::lead(x), y = y, yend = dplyr::lead(y)), size = 0.01)
#> Warning: Removed 1 rows containing missing values (geom_segment).
正如您所看到的,它只是链接您创建的点。 最后一个点没有下一个,所以最后一个段被删除(参见warning
)
第二个,我认为更好,更ggplot
ish,利用stat_function()
。
library(ggplot2)
f = function(x) .79 - (.06 * dnorm(x, 52.65, 10.67)) / .05
hdiLo <- 31.88
hdiHi <- 73.43
yComb <- seq(hdiLo, hdiHi, length = 75)
ggplot() +
xlim(-0.2, 113.2) +
ylim(0.58, 1) +
stat_function(data = data.frame(yComb), fun = f) +
coord_flip()
这构建了一个合适的函数( y = f(x)
),绘制它。 请注意,它是在X轴上构建然后翻转的。 因此, xlim
和ylim
是倒置的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.