[英]A ggplot2 equivalent of the lines() function in basic plot
For reasons I won't go into I need to plot a vertical normal curve on a blank ggplot2 graph. 由于我不会涉及的原因,我需要在空白ggplot2图上绘制垂直法线曲线。 The following code gets it done as a series of points with x,y coordinates 以下代码将其作为一系列带有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)
The curve is clearly discernible but is a series of points. 曲线清晰可辨但是一系列要点。 The lines()
function in basic plot would turn these points into a smooth line. 基本图中的lines()
函数会将这些点转换为平滑线。
Is there a ggplot2 equivalent? 是否有ggplot2等价物?
I see two different ways to do it. 我看到了两种不同的方法。
The first uses geom_segment
to 'link' each point with its next one. 第一个使用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).
As you can see it just link the points you created. 正如您所看到的,它只是链接您创建的点。 The last point does not have a next one, so the last segment is removed (See the warning
) 最后一个点没有下一个,所以最后一个段被删除(参见warning
)
The second one, which I think is better and more ggplot
ish, utilize stat_function()
. 第二个,我认为更好,更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()
This build a proper function ( y = f(x)
), plot it. 这构建了一个合适的函数( y = f(x)
),绘制它。 Note that it is build on the X axis and then flipped. 请注意,它是在X轴上构建然后翻转的。 Because of this the xlim
and ylim
are inverted. 因此, xlim
和ylim
是倒置的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.