Search code examples
rggplot2facet

How to split columns and plot a graph using facet_wrap?


https://www.kaggle.com/shivamb/netflix-shows-and-movies-exploratory-analysis contains the data set. (2.13MB)

I am trying to split the country column from the netflix data set and plot a faceted bar plot representing Movies from three countries.

The reproducible code is as follws:-

library(tidyverse)
library(scales)
library(lubridate)

netflix_tbl <- read.csv("netflix_titles_nov_2019.csv")

netflix_wrangled_tbl <- netflix_tbl%>%
    mutate(date_added = dmy(date_added), 
           date = day(date_added), month = month(date_added), year = year(date_added),
           count = readr::parse_number(as.character(duration)),
           show_type = stringr::str_remove(duration, as.character(count)))

netflix_wrangled_tbl %>%
    filter(type == "Movie") %>% 
    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 = 24)%>%
  ggplot(aes(y = tidytext::reorder_within(cast, n, country), x = n))+
  geom_col() +
  tidytext::scale_y_reordered() +
  facet_wrap(~country, scales = "free")

The resultant output is,

enter image description here

The expected output is:-

enter image description here

May I know where I am going wrong and how to achieve the expected output? Thanks.


Solution

  • Try modifying the last fragment of your code with this:

    netflix_wrangled_tbl %>%
      filter(type == "Movie") %>% 
      separate_rows(country, sep = ",")%>% 
      filter(country == "India" | country == "United States"| country == "United Kingdom")%>%
      separate_rows(cast, sep = ",")%>%
      filter(cast!="") %>%
      # Count by country and cast
      count(country, cast)%>%
      group_by(country) %>% arrange(desc(n)) %>%
      group_by(country) %>%
      slice(seq_len(24)) %>%
      ggplot(aes(y = tidytext::reorder_within(cast, n, country), x = n))+
      geom_col() +
      tidytext::scale_y_reordered() +
      facet_wrap(~country, scales = "free")
    

    enter image description here