user35131
user35131

Reputation: 1134

How do i plot a graph in ggplot 2 using values from a dataframe and converting them to rounded percent label

I have these values

PCT_Asian | PCT_Black | PCT_Hispanic | PCT_White | PCT_Other
.26554     .25454     .145454         .22454      .23123

I would like to see a bar plot where the x axis labels under each bin

PCT_Asian to Asian
PCT_Black to Black
Pct_White to White and so on.....

Also converts the values to proper percent labels

27%, 25%, 15%, 22%, and 23%

Upvotes: 0

Views: 26

Answers (1)

Roman
Roman

Reputation: 17648

you can try

library(tidyverse)
a <- str_split("PCT_Asian | PCT_Black | PCT_Hispanic | PCT_White | PCT_Other", "[|]", simplify = T) %>% str_trim(.)
b <- str_split(".26554     .25454     .145454         .22454      .23123", " ", simplify = T) %>% as.numeric(.) %>% na.omit(.)
tibble(a, b) %>% 
  mutate(x = str_remove(a, "PCT_")) %>% 
  ggplot(aes(x, b)) + 
   geom_col() + 
   scale_y_continuous(labels = scales::percent)

enter image description here

Upvotes: 1

Related Questions