-1

I have simple data on reading news by "Country" so two variables. I would like to make a horizontal bar chart that would show a percentage of answers "Read" news and "Otherwise" by country. Should I transform the data first or there is a special package for bar charts with that kind of data?

My data look like that:

Country  News
UK       Read
UK       Otherwise
UK       Read
FR       Read
FR       Otherwise
FR       Otherwise
DE       Read
DE       Read
DE       Read
DK       Read
DK       Read
DK       Otherwise
Laura
  • 306
  • 3
  • 12

1 Answers1

1

let the original data frame be df

library(dplyr)
library(tidyr)

df2 <- df %>% 
   group_by(Country, News) %>% 
   tally() %>% 
   complete(News, fill = list(n = 0)) %>% 
   mutate(Percentage = n / sum(n) * 100)


ggplot(df2, aes(News, Percentage, fill = Country) + 
   geom_bar(stat = 'identity', position = 'dodge') +
   theme_bw()+coord_flip()
user2510479
  • 1,528
  • 13
  • 17
  • The OP requested a horizontal bar chart. And BTW, it would be helpful to provide an image of the plot with your answer. Thank you. – Uwe Mar 21 '17 at 23:35
  • Perfect solution, thank you! I also have a suggestion for the bar chart `p <- ggplot(df2, aes(x = V2, y = n, fill = news)) + geom_bar(stat = "identity", position = "fill", width = .7) + coord_flip() + theme_grey()` – Laura Mar 21 '17 at 23:43
  • Edited to make bars horizontal – user2510479 Mar 22 '17 at 03:13
  • @user2510479 thank you. Do you why some countries obtained percentage like 1.0400 that is not bounded in [0,1]? – Laura Mar 22 '17 at 13:23