[英]ggplot2 geom_bar position failure
我現在用的是..count..
轉型geom_bar
並得到警告position_stack需要非重疊X間隔當我的一些類別的有幾個計數。
最好使用一些模擬數據來解釋(我的數據涉及方向和風速,我保留與之相關的名稱)
#make data
set.seed(12345)
FF=rweibull(100,1.7,1)*20 #mock speeds
FF[FF>60]=59
dir=sample.int(10,size=100,replace=TRUE) # mock directions
#group into speed classes
FFcut=cut(FF,breaks=seq(0,60,by=20),ordered_result=TRUE,right=FALSE,drop=FALSE)
# stuff into data frame & plot
df=data.frame(dir=dir,grp=FFcut)
ggplot(data=df,aes(x=dir,y=(..count..)/sum(..count..),fill=grp)) + geom_bar()
這很好,結果圖顯示了根據速度分組的方向的頻率。 具有最小計數的速度等級(此處為“[40,60”“)將具有5個計數是相關的。
然而,更多速度等級會導致警告。 例如,有
FFcut=cut(FF,breaks=seq(0,60,by=15),ordered_result=TRUE,right=FALSE,drop=FALSE)
最少計數的速度等級(現為“[45,60)”)只有3個計數,ggplot2會發出警告
position_stack需要不重疊的x區間
並且該圖將顯示沿x軸展開的此類別中的數據。 似乎5是一個組正常工作的最小大小。
我很想知道這是一個功能還是stat_bin
的錯誤( geom_bar
正在使用)或者我只是濫用geom_bar
。
此外,任何建議如何解決這個將不勝感激。
誠摯
發生這種情況是因為df$dir
是數字,因此ggplot對象采用連續的x軸,而美學參數group
基於唯一已知的離散變量( fill = grp
)。
結果,當grp = [45,60)
中沒有那么多的dir
值時,ggplot會對每個條的寬度感到困惑。 如果我們將情節分成不同的方面,這在視覺上會變得更加明顯:
ggplot(data=df,
aes(x=dir,y=(..count..)/sum(..count..),
fill = grp)) +
geom_bar() +
facet_wrap(~ grp)
> for(l in levels(df$grp)) print(sort(unique(df$dir[df$grp == l])))
[1] 1 2 3 4 6 7 8 9 10
[1] 1 2 3 4 5 6 7 8 9 10
[1] 2 3 4 5 7 9 10
[1] 2 4 7
我們還可以手動檢查排序的df$dir
值之間的最小差異是前三個grp
值是1,而最后一個值是2。 因此,默認條寬度更寬。
以下解決方案都應該達到相同的效果:
1.在geom_bar()
為所有組明確指定相同的條寬 :
ggplot(data=df,
aes(x=dir,y=(..count..)/sum(..count..),
fill = grp)) +
geom_bar(width = 0.9)
2.在將dir
傳遞給aes(x = ...)
之前將其轉換為分類變量 :
ggplot(data=df,
aes(x=factor(dir), y=(..count..)/sum(..count..),
fill = grp)) +
geom_bar()
3.指定group
參數應基於df$dir
和df$grp
:
ggplot(data=df,
aes(x=dir,
y=(..count..)/sum(..count..),
group = interaction(dir, grp),
fill = grp)) +
geom_bar()
這並沒有直接解決問題,因為我也沒有得到重疊值的結果,但它是一個dplyr
解決方法,無論如何可能會變得更靈活。
而不是依靠geom_bar
來獲取切割因子並通過..count../sum(..count..)
給你股票,你可以輕松地自己..count../sum(..count..)
計算這些股票,然后繪制你的酒吧。 我個人喜歡對我的數據進行這種控制,以及我正在繪制的內容。
首先,我將dir
和FF
放入數據幀/ tbl_df
,然后剪切FF
。 然后count
讓我組的數據通過dir
和grp
和計數觀測次數為這兩個變量的每一種組合,然后計算每個份額n
過的和n
。 我正在使用geom_col
,就像geom_bar
,但當你的aes
有y
值時。
library(tidyverse)
set.seed(12345)
FF <- rweibull(100,1.7,1) * 20 #mock speeds
FF[FF > 60] <- 59
dir <- sample.int(10, size = 100, replace = TRUE) # mock directions
shares <- tibble(dir = dir, FF = FF) %>%
mutate(grp = cut(FF, breaks = seq(0, 60, by = 15), ordered_result = T, right = F, drop = F)) %>%
count(dir, grp) %>%
mutate(share = n / sum(n))
shares
#> # A tibble: 29 x 4
#> dir grp n share
#> <int> <ord> <int> <dbl>
#> 1 1 [0,15) 3 0.03
#> 2 1 [15,30) 2 0.02
#> 3 2 [0,15) 4 0.04
#> 4 2 [15,30) 3 0.03
#> 5 2 [30,45) 1 0.01
#> 6 2 [45,60) 1 0.01
#> 7 3 [0,15) 6 0.06
#> 8 3 [15,30) 1 0.01
#> 9 3 [30,45) 2 0.02
#> 10 4 [0,15) 6 0.06
#> # ... with 19 more rows
ggplot(shares, aes(x = dir, y = share, fill = grp)) +
geom_col()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.