Dr. Know Nothing
Dr. Know Nothing

Reputation: 55

label and change colors to bar charts using ggplot2

I am trying to replicate the bar charts as the figure 1. in this paper (https://link.springer.com/content/pdf/10.1007/s10461-020-02820-6.pdf) and my data look like

dat <- read.table(text = "    item_1 item_2 item_3 item_4 item_5

StronglyAgree   40  30 20 10 45
Agree   30  30 45 30 5
Netural   20  20 5 10 25
Disagree   5  10 8  25 15
StronglyDisagree   5  10 15 25 10",sep = "",header = TRUE)

and I have tried the code, which did not quite give me exactly the figure I want

datm <- dat %>% 
  mutate(ind = factor(row_number())) %>%  
  gather(variable, value, -ind)

ggplot(datm, aes(x = variable, y = value, fill = ind)) + 
    geom_bar(position = "fill",stat = "identity", show.legend = FALSE) +
    scale_y_continuous(labels = scales::percent_format())+
  coord_flip()

I would like to:

  1. if possible, change the name 'item 1,item2...' to exactly the question
  2. recode the colors, ideally change 'strongly disagree & disagree' to the red theme, neutral to grey, and agree & strongly agree to the green theme
  3. add the legend

thank you so much!!

Upvotes: 1

Views: 268

Answers (1)

Samet S&#246;kel
Samet S&#246;kel

Reputation: 2690

you can manipulate the colors and texts in this template ;

ggplot(datm, aes(x = variable, y = value, fill = ind)) + 
    geom_bar(position = "fill",stat = "identity") +
    scale_y_continuous(labels = scales::percent_format())+
    scale_x_discrete(labels=c('item_5'='You','item_4'='Can','item_3'='Type','item_2'='Whatever','item_1'='You Want'))+
    scale_fill_manual(breaks = waiver(),
                      values = c('red','yellow','grey','lightgreen','green'),
                      labels = c('strongly disagree','disagree','neutral','agree','strongly agree'))+
    coord_flip()

enter image description here

Upvotes: 1

Related Questions