Home > database >  ggplot: adding text to inside and label outside?
ggplot: adding text to inside and label outside?

Time:04-30

Hi I would like to create a pie chart the has the total frequency inside the pie chart but on the outside I would like to add the label?

for example:

temp = structure(list(Var1 = c("diet", "water", "pepsi", "coke", "7_up", 
"sprite", "none"), Freq = c(351L, 212L, 71L, 444L, 524L, 193L, 
53L), per = c(0.189935064935065, 0.114718614718615, 0.0384199134199134, 
0.24025974025974, 0.283549783549784, 0.104437229437229, 0.0286796536796537
)), row.names = c(1L, 3L, 5L, 7L, 9L, 11L, 13L), class = "data.frame")

Here I can create the the plot but the labels are all jumbled up.

ggplot(data = temp,
       aes(x = "", y = per, fill = Var1))  
  geom_col()  
  geom_text(aes(label = Freq  ),
            position = position_stack(vjust = 0.5),
            color = "grey20", size = 12, fontface = "bold"  )  
  coord_polar(theta = "y", direction = -1 )  

  theme_void()  
  theme(legend.position = "none",
        legend.direction = "vertical")   

  theme ( legend.text      =element_text(size=12),
          legend.title = element_text(size=12) )  
  geom_label_repel(
    aes(
      label = Var1, y=per
    ),  box.padding = 0.25
  )

the chart looks like this.

enter image description here

CodePudding user response:

Instead of putting x = "", you can put x = 1 for the bars and then x = 1.5 or some other value for the labels. Essentially try to make bar chart with the labels outside the bars, then if you turn to polar coordinates, you should get the desired output

ggplot(data = temp,
       aes(x = 1, y = per, fill = Var1))  
    geom_col()  
    geom_text(aes(label = Freq),
              position = position_stack(vjust = 0.5),
              color = "grey20", fontface = "bold"  )  
    geom_label(aes(x = 1.5, label = Var1), 
               position = position_stack(vjust = 0.5))   
    coord_polar(theta = "y", direction = -1 )  
    theme_void()  
    theme(legend.position = "none",
          legend.direction = "vertical")   
    theme (legend.text = element_text(size=12),
            legend.title = element_text(size=12) )

enter image description here

  • Related