簡體   English   中英

基本圖中的ggplot2等效的lines()函數

[英]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

第一個使用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

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()

這構建了一個合適的函數( y = f(x) ),繪制它。 請注意,它是在X軸上構建然后翻轉的。 因此, xlimylim是倒置的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM