作者jackylikebmw (Tsai Chia Yu)
看板R_Language
标题[问题] ggplot绘制圆饼图问题
时间Tue Apr 17 17:56:06 2018
[问题类型]:
程式谘询(我想用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://webptt.com/cn.aspx?n=bbs/R_Language/M.1523958970.A.484.html
1F:推 F0011010101: 一个方式是 把 %>% arrange(per)拿掉,就是不要排序 04/17 21:23
2F:→ F0011010101: 然後把geom_text的地方 y=1-( cumsum(per) - per/2 ) 04/17 21:25
3F:→ F0011010101: 你会发现 虽然你前面用per对资料排序 04/17 21:28
4F:→ F0011010101: 但fill=a的顺序 还是照a1,a2,a3这样的顺序 04/17 21:29
6F:→ celestialgod: 感觉是你後面算y出错 04/17 21:47
7F:→ celestialgod: 试着不要在算一次,前面算完 04/17 21:47
8F:→ F0011010101: 如果坚持要保留arrange(per) 那geom_bar的地方要改成 04/17 22:11
9F:→ F0011010101: fill = ordered(a, levels = a) 04/17 22:11
10F:→ F0011010101: 如果比例想要顺时针递增 arrange(desc(per))反过来排 04/17 22:14
11F:→ F0011010101: 总之 不管怎样 geom_text的y应该是一定要改的 04/17 22:15
12F:→ jackylikebmw: 感谢回应~ 05/16 17:58