如何在R中绘制饼图

时间:2017-06-08 07:34:00

标签: r ggplot2

我在R中有以下数据框,并希望从中制作饼图

berth_day count
Friday    74
Monday    95
Saturday  126
Sunday    114
Thursday  62
Tuesday   85

我在R

中做了以下事情
ggplot(aes(x=berth_day, y=count))+
geom_bar(width =1)
+ coord_polar(theta = "y")

但是,它给了我以下错误

> ggplot(aes(x=berth_day, y=count))+
+   geom_bar(width =1)
Error: ggplot2 doesn't know how to deal with data of class uneval
>   + coord_polar(theta = "y")
Error in +coord_polar(theta = "y") : invalid argument to unary operator

我怎样才能在R?

中完成

2 个答案:

答案 0 :(得分:1)

目前尚不清楚OP的数据是来自管道还是忘了添加ggplot来电

df1N <- df1 %>% mutate(berth_day = factor(berth_day))

ggplot(df1N,  aes(x=berth_day, y=count, fill = berth_day))+
    geom_bar(width =1, stat = "identity")+ 
    coord_polar(theta = "y")

enter image description here

正如@GGamba在评论中所说,geom_bar已弃用,而是使用geom_col

ggplot(df1N,  aes(x=berth_day, y=count, fill = berth_day))+
    geom_col(width=1)+ 
    coord_polar(theta = "y")

答案 1 :(得分:1)

以这种方式构建一个合适的馅饼:

library(ggplot2)
ggplot(df1, aes(x = 1, y = count, fill = berth_day))+
    geom_col(position = 'stack', 
             show.legend = F) +
    geom_text(aes(label = paste(berth_day, ': ', count)), 
               position = position_stack(vjust = .5)) +
    coord_polar(theta = "y") +
    theme_void()

数据:

df1 <- read.table(text = 'berth_day count
Friday    74
                  Monday    95
                  Saturday  126
                  Sunday    114
                  Thursday  62
                  Tuesday   85', h = T)