1

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
Homer Jay Simpson
  • 1,043
  • 6
  • 19

4 Answers4

2

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 reprex package (v2.0.1)

Carl
  • 4,232
  • 2
  • 12
  • 24
1

In place of if_else you can use case_when which allows to vectorise multiple if_else() statements like

library(tidyverse)

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

DAT  %>% 
  mutate(C2 = case_when(C1 == TRUE ~ "OK",
            C1 == FALSE ~ "Not OK")) %>% 
  ggplot(aes(C2, fill = C2)) + 
  geom_bar() +
  labs(fill = "Check")

enter image description here

UseR10085
  • 7,120
  • 3
  • 24
  • 54
0

See this answer:

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

ggplot(
  DAT,
  aes(C1,color="lightblue")) + 
  geom_bar(aes(color="black", fill = "red")) +
  scale_x_discrete(
    breaks = c(FALSE, TRUE),
    labels = c("not ok", "ok"))
tauft
  • 546
  • 4
  • 13
0

To have variables appear in your legends, avoid fixing the colour, e.g. fill = "lightblue", instead use the variable you want, e.g. fill = C1

id = c("A","B","C","D","E")
C1 = c(T,F,T,F,T)
DAT = tibble(id,C1);DAT
    
ggplot(DAT,aes(C1)) + 
  geom_bar(aes(fill = C1)) +
  scale_x_discrete(labels = c("Not OK", "OK")) +
  scale_fill_manual(labels = c("Not Ok", "OK"), values = c("darkred", "darkblue")) +
  labs(fill = "Anything here")

enter image description here

Tech Commodities
  • 1,884
  • 6
  • 13