1. ホーム
  2. r

[解決済み] 美学は長さ1か、データと同じ長さでなければならないProblems

2022-02-05 21:07:18

質問

X値を測定値のサブセット、Y値を測定データの別のサブセットとしてプロットを作成したいのですが。

以下の例では、4つの商品p1, p2, p3, p4があります。それぞれ、傾き、色、バージョンに応じて価格が設定されています。 P3製品(Y軸)とP1製品(X軸)を描写する多面的なプロットを作成したいのですが、どうすればよいでしょうか?

以下のように試したのですが、以下のようなエラーが出て惨敗しました。

エラーです。美学は長さ1であるか、またはそれと同じ長さでなければなりません。 dataProblems:subset(price, product == "p1"), subset(price, product) == p3") となります。

library(ggplot2)
product=c("p1","p1","p1","p1","p1","p1","p1","p1","p2","p2","p2","p2","p2","p2","p2","p2","p3","p3","p3","p3","p3","p3","p3","p3","p4","p4","p4","p4","p4","p4","p4","p4")
skew=c("b","b","b","b","a","a","a","a","b","b","b","b","a","a","a","a","b","b","b","b","a","a","a","a","b","b","b","b","a","a","a","a")
version=c(0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2)
color=c("C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2")
price=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32)
df = data.frame(product, skew, version, color, price)
# First plot all the data
p1 <- ggplot(df, aes(x=price, y=price, colour=factor(skew))) + geom_point(size=2, shape=19)
p1 <- p1 + facet_grid(version ~ color)
p1 # This gavea very good plot. So far so good
# Now plot P3 vs P1
p1 <- ggplot(df, aes(x=subset(price, product=='p1'), y=subset(price, product=='p3'), colour=factor(skew))) + geom_point(size=2, shape=19)
p1
# failed with: Error: Aesthetics must either be length one, or the same length as the dataProblems:subset(price, product == "p1"), subset(price, product == "p3")

これは私が期待している結果です。

解決方法は?

問題は skew がサブセット化されていない colour=factor(skew) ということで、間違った長さになっています。そのため subset(skew, product == 'p1') と同じです。 subset(skew, product == 'p3') この場合、どちらのサブセットを使用するかは問題ではありません。ということで、問題を解決することができます。

p1 <- ggplot(df, aes(x=subset(price, product=='p1'),
                     y=subset(price, product=='p3'),
                     colour=factor(subset(skew, product == 'p1')))) +
              geom_point(size=2, shape=19)

なお、ほとんどのRユーザは、こちらの方が簡潔であると書くだろう。

p1 <- ggplot(df, aes(x=price[product=='p1'],
                     y=price[product=='p3'],
                     colour=factor(skew[product == 'p1']))) +
              geom_point(size=2, shape=19)