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

R ggplot-如何显示百分比比例和总和,r,ggplot2,plot,visualization,R,Ggplot2,Plot,Visualization,我的代码: 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) + t

我的代码:

  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'))
我的情节:

示例数据:

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

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

您几乎做到了。因此,对于百分比,您需要添加另一列和计算出的百分比,并将其用作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,aes(x=month,y=properties+0.15,label=properties),
inherit.aes=FALSE,size=2)
#开始时转换为数字
数据%mutate(属性=as.numeric(属性))
#计算百分比
数据%按(月)分组%>%变异(perc=四舍五入(100*属性/总和(属性),1))
#用sum生成另一个数据帧
sumdata%按月份分组%>%汇总(属性=总和(属性))
#几乎相同的情节
g=ggplot(数据=数据,aes(x=月份,y=属性,填充=显示))+
主题灯()
几何坐标(α=0.8)+
几何图形文本(aes(标签=perc,组=c(显示)),
位置=位置\堆栈(vjust=.5),vjust=-.2,size=2)+
主题(axis.text.x=元素\文本(角度=45,hjust=1,vjust=1,大小=6),
legend.position=“底部”,
axis.title=元素\文本(大小=8),
axis.title.y.left=元素\文本(大小=10))+
ylab(“财产”)+xlab(“月份”)+
刻度(填充)手动(“显示”,值=c(“是”='#B3',“否”='#8080ff'))+
geom_文本(数据=sumdata,aes(x=月,y=属性+0.15,标签=属性),
inherit.aes=FALSE,size=2)

例如,请使用
dput(data)
包含一些数据。我刚刚在说明中添加了示例数据,“属性”似乎从列中丢失了?@brtk在表中显示示例数据并不理想,因为我们无法将其轻松粘贴到IDE中,并且它缺少类型信息。请按照建议使用
dput(数据)
。如果数据太多(或机密),请使用“``head(data)%>%dput()```。我更正了属性