3

このデータセットがあるとしましょう:

x <- rnorm(1000)
y <- rnorm(1000, 2, 5)
line.color <- sample(rep(1:4, 250))
line.type <- as.factor(sample(rep(1:5, 200)))

data <- data.frame(x, y, line.color, line.type)

line.type と line.color の相互作用によって、x 変数グループと y 変数グループをプロットしようとしています。さらに、line.type を使用して線種を指定し、line.color を使用して色を指定したいと考えています。これを書くと:

ggplot(data, aes(x = x, y = y, group = interaction(line.type, line.color), colour = line.color, linetype = line.type)) + geom_line()

動作しますが、次のように aes_string を使用しようとすると:

interact <- c("line.color", "line.type")
inter <- paste0("interaction(", paste0('"', interact, '"', collapse = ", "), ")")

ggplot(data, aes_string(x = "x", y = "y", group = inter, colour = "line.color", linetype = "line.type")) + geom_line()

エラーが発生します:

Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line

私は何を間違っていますか?プロットする変数がたくさんあるので、aes_string を使用する必要があります。

4

2 に答える 2

3

上記のコメントで、いくつかの点で私が間違っていたことが判明しました。これはうまくいくようです:

data$inter <- interaction(data$line.type,data$line.color)
ggplot(data, aes_string(x = "x", y = "y", group = "inter",colour = "line.color",linetype = "line.type")) + geom_line()

(一点鎖線/点線内でさまざまな色などを指定するグラフについて、私は完全に間違っていました。)

interactionただし、これは、内部のコードの解析に依存することaes_string()は一般的に悪い考えであるというわずかな証拠だと思います。私の推測では、ggplotaes_string()が複雑なケースで与えているものを解析しようとする試みに小さなバグがあり、破線/点線でさまざまな美学を求めているように見える順序で物事を評価します。

于 2013-10-16T18:54:18.007 に答える
2

あなたはほとんどそこにいた

inter <- paste0("interaction(", paste0('"', interact, '"', collapse = ", "), ")")

ただし、 が機能するには、aes_stringを呼び出す場合に機能する文字列を渡す必要がありaesます。つまり、引数を文字列として内部に持つ必要はありませんinteraction。string を作成します"interaction(line.color, line.type)"。したがって

 inter <- paste0('interaction(', paste0(interact, collapse = ', ' ),')')
 # or
 # inter <- sprintf('interaction(%s), paste0(interact, collapse = ', '))
 # the result being
 inter
 ## [1] "interaction(line.color, line.type)"

 # and the following works
 ggplot(data, aes_string(x = "x", y = "y", 
    group = inter, colour = "line.color", linetype = "line.type")) + 
    geom_line()
于 2013-10-16T23:03:42.673 に答える