[問題] ggplot繪製圓餅圖問題

看板R_Language作者 (Tsai Chia Yu)時間6年前 (2018/04/17 17:56), 編輯推噓1(1011)
留言12則, 3人參與, 6年前最新討論串1/1
[問題類型]: 程式諮詢(我想用R 做某件事情,但是我不知道要怎麼用R 寫出來) [軟體熟悉度]: 使用者(已經有用R 做過不少作品) [問題敘述]: 我目前想要透過ggplot繪製圓餅圖,上網看了很多範例 但是發現套用到我的檔案上時,在圖上繪製百分比時會出現錯誤 好像是當有較大百分比位數時,會有一些錯誤,想要請各位幫忙~ [程式範例]: #以下為stackoverflow範例 #https://stackoverflow.com/questions/45657990 library(dplyr) library(ggplot2) data <- data.frame(a=c("a1","a1","a2","a3","a1","a2","a3","a4", "a2","a1","a5","a4","a3"),b=1:13) data <- data %>% group_by(a) %>% count() %>% ungroup() %>% mutate(per=`n`/sum(`n`)) %>% arrange(per) data$label <- scales::percent(data$per) ggplot(data=data)+ geom_bar(aes(x="", y=per, fill=a), stat="identity", width = 1)+ coord_polar("y", start=0)+ theme_void()+ geom_text(aes(x=1, y = cumsum(per) - per/2, label=label)) #在這個範例中,程式是正常顯示的 # https://imgur.com/85FnFOr
#但是當我將某一比例加大時,畫圖就出現錯誤 library(dplyr) library(ggplot2) data <- data.frame(a=c("a1","a1","a2","a3","a1","a2","a3","a4", "a2","a1","a5","a4",rep("a3",20)),b=1:32) data <- data %>% group_by(a) %>% count() %>% ungroup() %>% mutate(per=`n`/sum(`n`)) %>% arrange(per) data$label <- scales::percent(data$per) ggplot(data=data)+ geom_bar(aes(x="", y=per, fill=a), stat="identity", width = 1)+ coord_polar("y", start=0)+ theme_void()+ geom_text(aes(x=1, y = cumsum(per) - per/2, label=label)) #https://imgur.com/7BHUOuq
[環境敘述]: R version 3.4.4 (2018-03-15) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows >= 8 x64 (build 9200) dplyr_0.7.4 ggplot2_2.2.1 [關鍵字]: ggplot , piechart , 圓餅圖 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.172.82.96 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1523958970.A.484.html

04/17 21:23, 6年前 , 1F
一個方式是 把 %>% arrange(per)拿掉,就是不要排序
04/17 21:23, 1F

04/17 21:25, 6年前 , 2F
然後把geom_text的地方 y=1-( cumsum(per) - per/2 )
04/17 21:25, 2F

04/17 21:28, 6年前 , 3F
你會發現 雖然你前面用per對資料排序
04/17 21:28, 3F

04/17 21:29, 6年前 , 4F
但fill=a的順序 還是照a1,a2,a3這樣的順序
04/17 21:29, 4F

04/17 21:47, 6年前 , 5F
04/17 21:47, 5F

04/17 21:47, 6年前 , 6F
感覺是你後面算y出錯
04/17 21:47, 6F

04/17 21:47, 6年前 , 7F
試著不要在算一次,前面算完
04/17 21:47, 7F

04/17 22:11, 6年前 , 8F
如果堅持要保留arrange(per) 那geom_bar的地方要改成
04/17 22:11, 8F

04/17 22:11, 6年前 , 9F
fill = ordered(a, levels = a)
04/17 22:11, 9F

04/17 22:14, 6年前 , 10F
如果比例想要順時針遞增 arrange(desc(per))反過來排
04/17 22:14, 10F

04/17 22:15, 6年前 , 11F
總之 不管怎樣 geom_text的y應該是一定要改的
04/17 22:15, 11F

05/16 17:58, 6年前 , 12F
感謝回應~
05/16 17:58, 12F
文章代碼(AID): #1QrSIwI4 (R_Language)