2016-08-04 7 views
1

私はggplot2で作成できるサニーキーのようなプロットを作成したいと思います。開始点と終了点の間に曲線があります。私はggplot2の開始点と終了点の間に曲線を補間する

library(ggplot2) 
ggplot(df) + 
    geom_path(aes(x= X, y= Y, group = Line)) 

have

ます:

df <- data.frame(Line = rep(letters[1:4], 2), 
       Location = rep(c("Start", "End"), each=4), 
       X = rep(c(1, 10), each = 4), 
       Y = c(c(1,3, 5, 15), c(9,12, 14, 6)), 
       stringsAsFactors = F) 

例::

Line Location X Y 
1 a Start 1 1 
2 a  End 10 9 

とこのようになりますプロットを作成します現在、私は次のようになり、データを持っていますデータが次のように表示されるようにしてください:

enter image description here

これは、データを設定するための別のオプションです:

df2 <- data.frame(Line = letters[1:4], 
        Start.X= rep(1, 4), 
        Start.Y = c(1,3,5,15), 
        End.X = rep(10, 4), 
        End.Y = c(9,12,14,6)) 

例:

Line Start.X Start.Y End.X End.Y 
1 a  1  1 10  9 

私はベースRのグラフィックスに曲線を追加する方法の例を見つけることができますこれらの例では、その曲線を描くためにポイント間のデータフレームを取得する方法を示していません。データ操作にdplyrを使用することをお勧めします。私は補間された点のテーブルを作成するためにfor-loopが必要になると思います。

これらの例は似ていますが、S字カーブを生成しない:

Plotting lines on map - gcIntermediate

http://flowingdata.com/2011/05/11/how-to-map-connections-with-great-circles/

は、事前にありがとうございます!

答えて

2

以下のコードは、ロジスティック関数を使用して曲線を作成しています。代わりに好きな機能を使うことができますが、これが主なアイデアです。私は、グラフィカルな目的以外では、2点から曲線を作成することは悪い考えであることに注意してください。それは、実際にその関係を意味するわけではないが、データが特定のタイプの関係を示すことを意味する。

df <- data.frame(Line = rep(letters[1:4], 2), 
       Location = rep(c("Start", "End"), each=4), 
       X = rep(c(1, 10), each = 4), 
       Y = c(c(1,3, 5, 15), c(9,12, 14, 6)), 
       stringsAsFactors = F) 

# logistic function for curved lines 
logistic = function(x, y, midpoint = mean(x)) { 
    ry = range(y) 
    if (y[1] < y[2]) { 
    sign = 2 
    } else { 
    sign = -2 
    } 
    steepness = sign*diff(range(x))/diff(ry) 
    out = (ry[2] - ry[1])/(1 + exp(-steepness * (x - midpoint))) + ry[1] 
    return(out) 
} 

# an example 
x = c(1, 10) 
y = c(1, 9) 
xnew = seq(1, 10, .5) 
ynew = logistic(xnew, y) 
plot(x, y, type = 'b', bty = 'n', las = 1) 
lines(xnew, ynew, col = 2, type = 'b') 

# applying the function to your example 
xnew = seq(min(df$X), max(df$X), .1) # new x grid 
m = matrix(NA, length(xnew), 4) # matrix to store results 

uniq = unique(df$Line) # loop over all unique values in df$Line 
for (i in seq_along(uniq)) { 
    m[, i] = logistic(xnew, df$Y[df$Line == uniq[i]]) 
} 
# base R plot 
matplot(xnew, m, type = 'b', las = 1, bty = 'n', pch = 1) 

# put stuff in a dataframe for ggplot 
df2 = data.frame(x = rep(xnew, ncol(m)), 
       y = c(m), 
       group = factor(rep(1:ncol(m), each = nrow(m)))) 

library(ggplot2) 
ggplot(df) + 
    geom_path(aes(x= X, y= Y, group = Line, color = Line)) + 
    geom_line(data = df2, aes(x = x, y = y, group = group, color = group)) 

enter image description here

+0

私は完全にこれがどのように機能するかを理解していないが、トリックを行うようです!あなたのコメントを書き留めておきます。これは、これが示唆している関係です。私はまた、あなたがこの質問に答えたスピードを認めたいと思っています。 – yake84

関連する問題