2016-05-25 7 views
0

私はこのように定義されたggplotグラフがあります。例えばカスタマイズ( beautiful image, ugly legendggplotグラフから外部変数への対話を抽出する方法は?

今、私は後でそれを再利用する変数に相互作用を抽出したいと思います:

x <- seq(0, 10, by = 0.1) 
y1 <- cos(x) 
y2 <- sin(x) 
df1 <- data.frame(x = x, y = y1, type = "sin", id = 1) 
df2 <- data.frame(x = x, y = y2, type = "cos", id = 2) 
df3 <- data.frame(x = 2, y = 0.5, type = "constant", id = 3) 
df4 <- data.frame(x = 4, y = 0.2, type = "constant", id = 4) 

combined <- rbind(df1, df2, df3, df4) 

ggplot(combined, aes(x, y, colour = interaction(type, id))) + geom_line() + 
    geom_point(data = subset(combined, type == "constant")) 

下図のように、これは非常にうまく機能は、凡例のスタイルまたはラベル)。

私は非常にナイーブな方法であることでした:

Error: Aesthetics must be either length 1 or the same as the data (2): x, y, colour

編集:ここでは は私が何ができる操作の一種である:編集

my.interaction <- interaction(combined$type, combined$id) 

ggplot(combined, aes(x, y, colour = my.interaction)) + geom_line() + 
    geom_point(data = subset(combined, type == "constant")) 

しかし、その後、私はエラーを持っています伝説の線種

displayed <- levels(factor(my.interaction)) 
line.style <- rep(1, length.out = length(displayed)) 
line.style[grep("constant", displayed)] <- 0 
ggplot(combined, aes(x, y, colour = interaction(type, id))) + geom_line() + 
    geom_point(data = subset(combined, type == "constant")) + 
    guides(colour=guide_legend(override.aes=list(linetype = line.style))) 

beautiful image, better legend

をしないこと:作品

ggplot(combined, aes(x, y, colour = my.interation) + geom_line() + 
    geom_point(data = subset(combined, type == "constant")) + 
    guides(colour=guide_legend(override.aes=list(linetype = line.style))) 

最後に、私はまた、例えば(形状や凡例ラベルを編集することができ"Id:1/Type:sin"または対話値に基づくラベルの他の高度な変換)を使用して、

+0

あなたは 'combined' data.frameに' my.interaction'を追加することに反対していますか?あなたは '$ my.interaction < - interaction(combined $ type、combined $ id)'を組み合わせることができます。あなたのアプローチはうまくいくでしょう。 – JasonAizkalns

+0

はい、私はこれを避けたいと思います。私がプロットしたいものに応じて、私は別のプロットで他のやりとりを使うかもしれません...したがって、私のデータフレームはやや冗長な情報で成長します。 – Ben

+1

もっと具体的にあなたのコメントの例を挙げることができますか?あなたの質問を編集/更新したいかもしれません。私はこれが[XY問題](http://meta.stackexchange.com/q/66377)かもしれないと思う。 – JasonAizkalns

答えて

0

これは動作します。データフレームに列を追加すると何が問題になりますか?

combined %>% mutate(my.interaction = paste(type, id, sep='.')) %>% 
    ggplot(aes(x, y, colour = my.interaction)) + geom_line() + 
    geom_point(data = subset(combined, type == "constant")) 

image from ggplot

+2

これは私が上記のコメントで提案したアプローチ/方法と同じです。元のポスターは、この行動を避けようとしていると述べています。 – JasonAizkalns

関連する問題