How to filter the data and plot a column chart using the facet wrap in r?

Viewed 1025

https://www.kaggle.com/shivamb/netflix-shows-and-movies-exploratory-analysis/notebook contains the data set. (File size is 2.1 MB)

I am looking the achieve the following things the data set - Identify the top 25 leading actors from the countries of United States, United Kingdom and India.

The code that I worked out is as follows,

library(tidyverse)
net_flix <- read.csv("netflix_titles_nov_2019.csv")

net_flix %>% 
    separate_rows(country, sep = ",")%>% 
    filter(country == "India"| country == "United States"| country == "United Kingdom")%>%
    separate_rows(cast, sep = ",")%>%
    count(cast)%>%
    slice_max(n, n = 25)%>%
    ggplot(aes(y = fct_reorder(cast, n), x = n))+
    geom_col()

The resultant output is as follows,

enter image description here

The expected output is as follows,(only the top part of the chart)

enter image description here

The attempt is made after reviewing the suggested question https://stackoverflow.com/questions/55864054/filtering-the-data-using-pickerinput-and-plotting-based-on-the-filtered-data-i

1 Answers

Try this. The issue with facet_wrap is that in order to facet by country you have to count by both cast and country. Also. To get the bars ordered in each facet I make use of tidytext::reorder_within and tidytext::scale_x_reordered:

library(tidyverse)
net_flix <- read.csv("netflix_titles_nov_2019.csv")

net_flix %>% 
  separate_rows(country, sep = ",")%>% 
  filter(country == "India"| country == "United States"| country == "United Kingdom")%>%
  separate_rows(cast, sep = ",")%>%
  # Count by country and cast
  count(country, cast)%>%
  slice_max(n, n = 25)%>%
  ggplot(aes(y = tidytext::reorder_within(cast, n, country), x = n))+
  geom_col() +
  tidytext::scale_y_reordered() +
  facet_wrap(~country, scales = "free")

This gives me this plot:

enter image description here

Related