Home > other >  In geom_text() how to shirnk text label size and not lost mapping attributes
In geom_text() how to shirnk text label size and not lost mapping attributes

Time:03-02

In below code, I add text to plot using geom_text() and mapping value to the size. But the label size is a little big compare to plot, How to shrink all of them to little size ? (and not lost the mapping attributes).Thanks!

library(tidyverse)
plot_data <- data.frame(category=c('A','A','B','C'),
                        sub_category=c('a1','a2','b1','c1'),
                        value=c(6,12,3,2))

plot_data %>% mutate(sub_category=if_else(category=='A',
                                          sub_category,category)) %>% 
  pivot_longer(names_to = 'title',values_to ='cat_region',-value) %>% 
  filter(!(title=='sub_category'&cat_region %in% c('B','C') )) %>% 
  group_by(title,cat_region) %>% 
  summarise(value_sum=sum(value)) %>% 
  ggplot(aes(x=title,y=value_sum,fill=cat_region,
             group=interaction(title,cat_region))) geom_col() 
  geom_text(position=position_stack(0.5),
            aes(size=value_sum,
                label=paste0(cat_region,'\n',value_sum))) 
  scale_x_discrete(
  limits=c('blank','blank','blank','category','sub_category')) 
  coord_polar(theta='y')

enter image description here

CodePudding user response:

As with other aesthetics you could set the range of possible values via the scale, e.g. in case of the size aesthetic via the range argument of scale_size. By reducing the maximum value for the range you could shrink all labels.

library(tidyverse)

plot_data %>%
  mutate(sub_category = if_else(category == "A",
    sub_category, category
  )) %>%
  pivot_longer(names_to = "title", values_to = "cat_region", -value) %>%
  filter(!(title == "sub_category" & cat_region %in% c("B", "C"))) %>%
  group_by(title, cat_region) %>%
  summarise(value_sum = sum(value)) %>%
  ggplot(aes(
    x = title, y = value_sum, fill = cat_region,
    group = interaction(title, cat_region)
  ))  
  geom_col()  
  geom_text(position=position_stack(0.5),
    aes(
      size = value_sum,
      label = paste0(cat_region, "\n", value_sum)
    )
  )  
  scale_x_discrete(
    limits = c("blank", "blank", "blank", "category", "sub_category")
  )  
  scale_size(range = c(1, 3.5))  
  coord_polar(theta = "y")
#> `summarise()` has grouped output by 'title'. You can override using the
#> `.groups` argument.

  • Related