简体   繁体   中英

Additional text of legend in r

I want to add additional text of percentage for each label in the legend as I can only add percentage in the sector diagram.

Here is my dataframe:

dat <- data.frame(
  time = factor(c("Breakfast","Breakfast","Lunch","Lunch","Dinner","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
  total_bill = c(12.75,14.8,17.23,13.8,12.5,18.9)
)

Here is my code:

d <- dat %>%
  group_by(time) %>%
  summarise(total=sum(total_bill)) %>%
  mutate(percent= total/sum(total)*100)

ggplot(d, aes(x = "",fill= time)) +
  geom_bar(aes(y=percent),width=1,stat="identity")+
  coord_polar(theta = "y")+
  geom_text(size=3,aes(y=percent,label = paste0(round(percent,digits = 2), "%")), 
            position = position_stack(vjust = 0.5),color="white")+
  scale_fill_manual(values = c("Lightblue","#AD7366","Lightgreen"))+
  labs(x="",y="",title = "\n",fill= "Libellé de famille de métier")+
  theme_classic() + theme(axis.line = element_blank(),  #pour obtenir le camambert propre
                          axis.text = element_blank(),
                          axis.ticks = element_blank(),
                          plot.title = element_text(hjust = 4, color = "#666666"))

My goal is to add additional percentage for each label in the legend for example: Breakfast (30.62%) , Lunch (34.49%) , Dinner(34.9%) . How can I achieve that?

Any help would be appreciated

You can add the parameter labels in scale_fill_manual :

ggplot(d, aes(x = "",fill= time)) +
geom_bar(aes(y=percent),width=1,stat="identity")+
coord_polar(theta = "y")+
geom_text(size=3,aes(y=percent,label = paste0(round(percent,digits = 2), "%")),
          position = position_stack(vjust = 0.5),color="white")+
scale_fill_manual(values = c("Lightblue","#AD7366","Lightgreen"),
                  labels = paste0(levels(d$time), ' (', round(d$percent,digits = 2), "%)"))+
labs(x="",y="",title = "\n",fill= "Libellé de famille de métier")+
theme_classic() + 
theme(axis.line = element_blank(),  #pour obtenir le camambert propre
      axis.text = element_blank(),
      axis.ticks = element_blank(),
      plot.title = element_text(hjust = 4, color = "#666666"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM