Home > Software engineering >  How to add percentages on histogram
How to add percentages on histogram

Time:12-12

I try to add percentages on the percentage histogram, my code is as follows, but it seems that something is wrong, I can't add the percentages to the graph correctly, and I can't get the perfect percentage histogram, please tell me what is wrong.

data<-data.frame(type=c("A","B","C"),
             loss=c(1.7,2.2,2.5,0.8,3.1,4.7,0.5,1.5,1.7,0.7,1.4,1.7),
             label=c("1","2","3","4"))
data<-data%>% 
      group_by(type)%>% 
      mutate(count=sum(loss))%>% 
      mutate(freq=round(100*loss/count,2))
ggplot(data,aes(label,loss ,fill=type)) 
geom_bar(stat="identity",position="fill",alpha = 0.9) 
theme_bw()   theme(panel.grid=element_blank()) 
theme(axis.ticks.length=unit(0.5,'cm'),
    legend.position = "top") 
scale_y_continuous(labels = scales::percent) 
geom_text(label = paste0(data$freq,"%"))

CodePudding user response:

  1. Your group_by variable must be "label".
  2. Don't multiply variable with 100. Multiply this variable inside paste() function.
  3. Use position_stack() function to center labels.
library(tidyverse)
data<-data.frame(type=c("A","B","C"),
                 loss=c(1.7,2.2,2.5,0.8,3.1,4.7,0.5,1.5,1.7,0.7,1.4,1.7),
                 label=c("1","2","3","4"))
data<-data%>% 
  group_by(label)%>% 
  mutate(count=sum(loss))%>% 
  mutate(freq=round(loss/count,2))

ggplot(data,aes(label,freq ,fill=type)) 
  geom_bar(stat="identity",position="fill",alpha = 0.9) 
  theme_bw()   theme(panel.grid=element_blank()) 
  theme(axis.ticks.length=unit(0.5,'cm'),
        legend.position = "top") 
  scale_y_continuous(labels = scales::percent) 
  geom_text(label = paste0(100*data$freq,"%"),  position = position_stack(vjust = 0.5))

CodePudding user response:

In geom_text(), you need to specify position = position_fill(). You will probably also want to adjust the heights so that the text appears in the middle of each bar, which you can do with vjust:

ggplot(data,aes(label,loss ,fill=type)) 
  ...
geom_text(label = paste0(data$freq,"%"),
          position = position_fill(vjust = 0.5))
  •  Tags:  
  • r
  • Related