Home > Blockchain >  In ggplot2 how to add angled label to donut chart
In ggplot2 how to add angled label to donut chart

Time:02-11

Below code can draw donut chart as the left one in attached image, how to change the label as the right one? Thanks!

library(tidyverse)
pie_data <- data.frame(category=c('A','B','C'),sales=c(70,25,40))
pie_data %>% ggplot(aes(x=1,y=sales,fill=category)) 
  geom_col() 
  scale_fill_brewer(direction = -1) 
  geom_text(position=position_stack(vjust=0.5),aes(label=paste0('Category ',category,':',sales))) 
  xlim(-1,2) 
  coord_polar(theta = 'y') 
  theme_void()

enter image description here

CodePudding user response:

You can use geom_textpath from the geomtextpath package, which is now on CRAN. Essentially just replace geom_text with geom_textpath and set the angle to 90 degrees.

library(geomtextpath)
library(dplyr)

pie_data <- data.frame(category = c('A', 'B', 'C'),
                       ,sales = c(70, 25, 40))
pie_data %>% ggplot(aes(x = 1, y = sales, fill = category))  
  geom_col()  
  scale_fill_brewer(direction = -1)  
  geom_textpath(position = position_stack(vjust = 0.5), angle = 90, size = 8,
            aes(label = paste0('Category ', category, ':', sales)))  
  xlim(-1, 2)  
  coord_polar(theta = 'y')  
  theme_void()

enter image description here

  • Related