Home > Software design >  ggplot: How to change labels to percentages on the graph?
ggplot: How to change labels to percentages on the graph?

Time:03-06

This is the head of my data set:

structure(list(Aasta = c(2011, 2012, 2013, 2014, 2015, 2016), 
tvs = c("Püsiv töövõimetus", "Püsiv töövõimetus", 
"Püsiv töövõimetus", "Püsiv töövõimetus", "Püsiv töövõimetus", 
"Püsiv töövõimetus"), Protsent = c(0.001, 0.018, 0.014, 
0.012, 0.013, 0.017)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))

This is my plot:

ggplot(merilen2, aes(y = Protsent, x = Aasta, color = tvs, label = Protsent)) 
  geom_line() 
  geom_point() 
  ggrepel::geom_label_repel(label.size = 0, 
                            label.padding = unit(0.3, "lines"), 
                            size = 3, 
                            min.segment.length = 0.2, 
                            vjust=-0.5,
                            show.legend = F) 
  scale_x_continuous(breaks = merilen2$Aasta, labels = merilen2$Aasta) 
  scale_color_manual(values = cen_cols) 
  labs(x = 'Aasta',
       y = 'Protsent',
       color = 'Töövõime staatus') 
  cen_theme()

This is the outcome right now:

enter image description here

I need the labels as percentages (with one decimal place) on the graph, but don't know who to do that.

CodePudding user response:

You can change the label in aes to -

label = paste0(round(Protsent * 100, 1), '%')

Complete code -

library(ggplot2)

ggplot(merilen2, aes(y = Protsent, x = Aasta, color = tvs, 
                     label = paste0(round(Protsent * 100, 1), '%'))) 
  geom_line() 
  geom_point() 
  ggrepel::geom_label_repel(label.size = 0, 
                            label.padding = unit(0.3, "lines"), 
                            size = 3, 
                            min.segment.length = 0.2, 
                            vjust=-0.5,
                            show.legend = F) 
  scale_x_continuous(breaks = merilen2$Aasta, labels = merilen2$Aasta) 
  labs(x = 'Aasta',
       y = 'Protsent',
       color = 'Töövõime staatus')

Removed scale_color_manual because cen_cols is not defined.

CodePudding user response:

Just add

  scale_y_continuous(label=scales::label_percent(.1))  
  • Related