2017-01-23 118 views
2

我想繪製使用ggplot散點圖下的等傾線,但我無法弄清楚如何正確使用stat_functionR:ggplot距離公式

的等值線是基於距離公式:

sqrt((x1-x2)^2 + (y1-y2)^2) 

和看起來像這些 同心圓,除了中心將是圖的原點:

enter image description here

我到目前爲止所嘗試的是在ggplot內調用距離函數(注意:我使用x1 = 1和y1 = 1,因爲在我真正的問題中,我也有固定值)

distance <- function(x, y) {sqrt((x - 1)^2 + (y - 1)^2)} 
ggplot(my_data, aes(x, y))+ 
    geom_point()+ 
    stat_function(fun=distance) 

但[R返回錯誤:

Computation failed in 'stat_function()': argument "y" is missing, with no default

如何正確餵養x和y的值stat_function,以便它繪製的距離公式的一般情節,與原點的中心?

+2

'stat_function'只能搞定計算ÿ功能。您需要將公式重新排列爲函數y = f(x)。 – Roland

回答

2

對於任何有點複雜的事情,我都避免使用stat函數。他們主要是爲了快速計算。它們通常僅限於根據x計算y。我只想用stat_contour而不是預先計算的數據和情節:

distance <- function(x, y) {sqrt((x - 1)^2 + (y - 1)^2)} 
d <- expand.grid(x = seq(0, 2, 0.02), y = seq(0, 2, 0.02)) 
d$dist <- mapply(distance, x = d$x, y = d$y) 

ggplot(d, aes(x, y)) + 
    geom_raster(aes(fill = dist), interpolate = T) + 
    stat_contour(aes(z = dist), col = 'white') + 
    coord_fixed() + 
    viridis::scale_fill_viridis(direction = -1) 

enter image description here

+0

謝謝,這是完美的!我如何將光柵顏色從viridis更改爲不同的調色板?我不熟悉::運算符。 –

+0

::只是避免必須首先使用庫(viridis)。請參閱幫助頁面和選項參數來更改調色板。 – Axeman