ggplot-如何显示百分比和总和

我的代码:

  ggplot(data=data,aes(x=month,y=as.numeric(properties),fill=show)) + 
  theme_light() + 
  geom_col(alpha=.8) +
        geom_text(aes(label=round(..y../1000,1),group = c(show)),position=position_stack(vjust=.5),vjust=-.2,size=2) +
  theme(axis.text.x = element_text(angle = 45,hjust = 1,vjust = 1,size=6),legend.position = "bottom",axis.title = element_text(size = 8),axis.title.y.left = element_text(size = 10)) +
  ylab("Properties") + xlab("Month") +
  scale_fill_manual("Show",values = c("YES" = '#b3b3b3',"NO" = '#8080ff'))

我的情节:

ggplot-如何显示百分比和总和

示例数据:

month   show properties
-------------------
2017-05 NO  2.1     
2017-05 YES 4.1     
2017-06 NO  2.1     
2017-06 YES 4.2
...

如何将每个组的总和更改为百分比比例,如何同时在每个条形上添加总单位和?

xkcxkcxkc 回答:ggplot-如何显示百分比和总和

您快到了。因此,对于百分比,您需要添加具有计算百分比的另一列,并将其用作geom_text()中的标签。对于总和,您需要单独计算它,并将其作为带有单独数据框的geom_text()引入:

# convert to numeric at the start
data <- data %>% mutate(properties=as.numeric(properties))
# calculate percentage
data <- data %>% group_by(month) %>% mutate(perc=round(100*properties/sum(properties),1))
# make another data frame with sum
sumdata <- data %>% group_by(month) %>% summarize(properties=sum(properties))

# almost the same plot with 
g = ggplot(data=data,aes(x=month,y=properties,fill=show)) + 
  theme_light() + 
  geom_col(alpha=.8) +
        geom_text(aes(label=perc,group = c(show)),position=position_stack(vjust=.5),vjust=-.2,size=2) +
  theme(axis.text.x = element_text(angle = 45,hjust = 1,vjust = 1,size=6),legend.position = "bottom",axis.title = element_text(size = 8),axis.title.y.left = element_text(size = 10)) +
  ylab("Properties") + xlab("Month") +
  scale_fill_manual("Show",values = c("YES" = '#b3b3b3',"NO" = '#8080ff'))+
 geom_text(data=sumdata,y=properties+0.15,label=properties),inherit.aes=FALSE,size=2)

enter image description here

本文链接:https://www.f2er.com/3161275.html

大家都在问