如何在 R 中處理錯誤:stat_count() can only have an x or y aesthetic?


為了處理錯誤:stat_count() can only have an x or y aesthetic,我們需要在 geom_bar 函式內部傳遞 stat="identity" 引數。因為我們沒有為條形圖傳遞計數,並且條形圖只能包含一個計數變數,所以需要 stat="identity" 以便 geom_bar 在 aes 中只考慮一個變數進行計數。請檢視下面的示例以瞭解區別。

示例

考慮以下資料框:

 線上演示

factor<-sample(0:2,20,replace=TRUE)
col<-sample(6:8,20,replace=TRUE)
count<-rpois(20,8)
df<-data.frame(factor,col,count)
df

輸出

   factor   col  count
1    2       7    7
2    0       8    8
3    0       6    9
4    0       7    8
5    1       7    10
6    0       6    12
7    2       6    10
8    1       6    8
9    0       6    9
10   0       7    8
11   0       8    3
12   2       8    11
13   1       7    14
14   0       7    10
15   1       8    13
16   0       8    5
17   2       8    10
18   2       7    8
19   1       6    9
20   2       8    9

載入 ggplot2 包併為因子列中的類別建立條形圖:

library(ggplot2)
ggplot(df,aes(factor,count,fill=col))+geom_bar()

錯誤 - stat_count() can only have an x or y aesthetic。

執行 `rlang::last_error()` 以檢視錯誤發生的位置。

使用 stat="identity" 建立條形圖:

示例

ggplot(df,aes(factor,count,fill=col))+geom_bar(stat="identity")

輸出

更新於: 2021年3月6日

3K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.