0

私は最近 R の使用を開始し、いくつかのドーナツでグラフを描画するために ggplot を使用しようとしています。次の質問 - ggplot Donut chartに触発されましたが、for サイクルでいくつかのリングを作成したいと考えています。

以下のテストデータフレームを作成しました:

library(ggplot2)

# Create test data.
rings<-data.frame(cat=c("A", "B", "C","D","E"), ring1=c(10, 60, 3, 70,5), ring2=c(20,30,8,15,1), ring3=c(5,40,80,22,10), ring4=c(10,60,16,25,20) )

for (y in 2:5){
# Add addition columns, needed for drawing with geom_rect.
rings[[y]] =  rings[[y]] / sum(rings[[y]])
rings[[y]] = cumsum(rings[[y]])
}

次のコードを使用して最初のドーナツを作成しました。

max<-4.5
min<-4

plot = ggplot(rings, aes(fill=cat, ymax=rings[[2]], ymin=c(0, head(rings[[2]], n=-1)), xmax=max, xmin=min)) +
geom_rect() +
coord_polar(theta="y") +
xlim(c(0, 10)) +
theme_bw() +
theme(panel.background = element_rect(fill = NA)) +
theme(panel.grid=element_blank()) +
theme(axis.text=element_blank()) +
theme(axis.ticks=element_blank()) +
labs(title="Customized ring plot")

for ループを使用せずにコードを記述した場合、すべてが正常に機能し、リングがうまく積み上げられ、リングが他のリングと明らかに異なることがわかります。

plot <- plot + geom_rect(data=rings, xmax=max, xmin=min, aes(ymax=rings[[2]], ymin=c(0,   head(rings[[2]], n=-1))))
min<-max
max<-max+0.5
plot <- plot + geom_rect(data=rings, xmax=max, xmin=min, aes(ymax=rings[[3]], ymin=c(0,     head(rings[[3]], n=-1))))
min<-max
max<-max+0.5
plot <- plot + geom_rect(data=rings, xmax=max, xmin=min, aes(ymax=rings[[4]], ymin=c(0, head(rings[[4]], n=-1))))
min<-max
max<-max+0.5
plot <- plot + geom_rect(data=rings, xmax=max, xmin=min, aes(ymax=rings[[5]], ymin=c(0,  head(rings[[5]], n=-1))))

print(plot)

for ループをコーディングすると、最初の 3 つのリングはカテゴリの分布が同じで、4 番目と最後のリングだけが異なります。

for (y in 3:5){
plot <- plot + geom_rect(data=rings, xmax=max, xmin=min, aes(ymax=rings[[y]], ymin=c(0, head(rings[[y]], n=-1))))
min<-max
max<-max+0.5
} 
print(plot)

これを行うためにさまざまな方法を試しましたが、問題が見えないようです。私は print() コマンドをうまく実装していると思います。また、次の質問に触発されて、 ggplotsを ggtables に変換しようとしました。

これが重複した投稿である場合は申し訳ありませんが、昨日と今日、他のいくつかのオプションを実装しようとしましたが、どれも機能していないようです.

4

0 に答える 0