Home > front end >  ggplot show the value rounded to one decimal place above the bar chart
ggplot show the value rounded to one decimal place above the bar chart

Time:07-07

I want to round the values above the bar chart to one decimal place. For example 14 should be 1.5 and not 1.52977.

This is how the bar chart looks right now

This is my code:

CPUE1 <- CPUE
CPUE1$Strecke <- factor (CPUE1$Strecke, levels = c('30/31', '14', '12', '10','1c','1bc', '1b'))

ggplot(CPUE1, aes(x= Strecke, y= CPUE, fill = Strecke )) 
  geom_bar(stat='identity', position = 'dodge') 
  theme_minimal() 
  geom_text (aes (label = CPUE), position=position_dodge(width=0.9), vjust=-0.25) 
  scale_fill_manual (values = 
                       c("12" = "green", "10"= "green",
                         "1c" = "green", "14"= "red",
                         "1b"= "red","1bc"= "red","30/31" = "red"))

CodePudding user response:

Add round to your geom_text:

library(tidyverse)

tribble(
  ~Strecke, ~CPUE,
  "1b", 1.333,
  "1c", 1.222,
  "1b", 2.666,
  "1c", 2.777
) |>
  mutate(Strecke = factor(Strecke)) |>
  ggplot(aes(Strecke, CPUE, fill = Strecke))  
  geom_bar(stat = "identity", position = "dodge")  
  theme_minimal()  
  geom_text(aes(label = round(CPUE, 1)), position = position_dodge(width = 0.9), vjust = -0.25)  
  scale_fill_manual(values = c("1b" = "red", "1c" = "blue"))

Created on 2022-07-07 by the reprex package (v2.0.1)

  • Related