Home > database >  How can i change the bar names in ggplot geom_bar and the legend title?
How can i change the bar names in ggplot geom_bar and the legend title?

Time:06-14

I have a data frame :

id = c("A","B","C","D","E")
C1 = c(T,F,T,F,T)
DAT = tibble(id,C1);DAT
ggplot(DAT,aes(C1,color="lightblue"))  geom_bar(aes(color="black",fill = "red"))

I want to create a bar chart like this one :

enter image description here

but i want to change the true to "ok" and false to "not ok" and also this renaming to appear in the legend at the right with title not colour but "Check". How can i do it in R ?

Optional

if i had a row with NA how i could change that ? For example:

id = c("A","B","C","D","E")
C1 = c(T,F,NA,F,T)
DAT = tibble(id,C1);DAT

CodePudding user response:

Like this?

library(tidyverse)

id <- c("A", "B", "C", "D", "E", "F")
C1 <- c(T, F, T, F, T, NA)
DAT <- tibble(id, C1)
DAT
#> # A tibble: 6 × 2
#>   id    C1   
#>   <chr> <lgl>
#> 1 A     TRUE 
#> 2 B     FALSE
#> 3 C     TRUE 
#> 4 D     FALSE
#> 5 E     TRUE 
#> 6 F     NA

DAT |>
  mutate(C1 = case_when(
    C1 == TRUE ~ "ok",
    C1 == FALSE ~ "not ok",
    TRUE ~ "not declared"
  )) |>
  ggplot(aes(C1, fill = C1))  
  geom_bar()  
  labs(fill = "Check")

Created on 2022-06-14 by the enter image description here

CodePudding user response:

See this enter image description here

  • Related