[英]Ordered Scatterplot with facets in ggplot with index
當我做類似的事情
plot(diamonds[order(diamonds$depth),"depth"])
我得到了以索引為x標簽的排序深度向量的圖。
與類似的結果
ggplot(diamonds[order(diamonds$depth),], aes(x=seq(depth), y=depth)) + geom_point()
現在我想通過說彩色來對圖形進行分面
ggplot(diamonds[order(diamonds$depth),], aes(x=seq(depth), y=depth)) + geom_point() + facet_grid(color~.)
但這不是我想要的,我實際上是想使繪圖在所有方面都保持有序(與總圖中的索引相同)。 順便說一句,我仍然想保留索引作為x軸的標簽。 正確的做法是什么?
我發現的一種方法是創建一個包含每個構面索引的新列:
counts <- table(diamonds$color)
xindex <- integer(sum(counts)) # preallocate to required length with zero values
ci <- 1 # cumulative count for vector indexing
for (i in counts) {
xindex[ci:(ci+i-1)] <- seq(i)
ci <- ci+i
}
diamonds$xindex <- xindex
ggplot(diamonds[order(diamonds$depth),], aes(x=xindex, y=depth))
+ geom_point()
+ facet_grid(color~.)
如果每種顏色恰好具有完全相同的計數,則可以使用以下代碼:
xindex <- sapply(table(diamonds$color), seq) # matrix columns corresponds color
diamonds$xindex <- c(xindex[,1:ncol(xindex)]) # convert from matrix to integer vector
ggplot(diamonds[order(diamonds$depth),], aes(x=xindex, y=depth))
+ geom_point()
+ facet_grid(color~.)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.