如何按年度电影发行数量重新排序基于Netflix数据绘制的堆叠条形图?
Got it, let's get your bar chart sorted exactly how you want it! Right now your plot shows years in chronological order, but we can adjust it to sort by the number of movies released each year (either ascending or descending). Here are two straightforward approaches using tidyverse tools:
Approach 1: Preprocess Data First (More Readable)
This method breaks out the sorting logic into a separate data step, making it easier to debug or modify later:
# Load required packages (tidyverse includes dplyr, ggplot2, and forcats) library(tidyverse) # Clean and sort the data netflix_sorted <- netflix %>% # Filter to 2000-2020 as before filter(release_year %in% 2000:2020) %>% # Convert year to character (as you had) mutate(release_year = as.character(release_year)) %>% # Calculate how many movies were released each year group_by(release_year) %>% mutate(movie_count = sum(type == "Movie")) %>% ungroup() %>% # Reorder the year factor by movie count (descending order) mutate(release_year = fct_reorder(release_year, -movie_count)) # Plot the sorted chart ggplot(netflix_sorted, aes(x = release_year, fill = type)) + geom_bar(position = "dodge") + coord_flip() + # Optional: Add clear labels labs( title = "Netflix Titles by Release Year (Sorted by Movie Count)", x = "Release Year", y = "Number of Titles", fill = "Content Type" )
Key Details:
fct_reorder()(from theforcatspackage) convertsrelease_yearinto an ordered factor. The-movie_countensures years with more movies appear first (remove the-if you want ascending order instead).- We calculate
movie_countwithsum(type == "Movie")to tally how many movies exist per year.
Approach 2: Inline Sorting (More Concise)
If you prefer to keep everything in one pipeline, you can handle the sorting directly inside the ggplot() call:
library(tidyverse) netflix %>% filter(release_year %in% 2000:2020) %>% mutate(release_year = as.character(release_year)) %>% ggplot( aes( # Reorder year by movie count directly in the aesthetic x = fct_reorder( release_year, type, # Custom function to count movies per year function(x) sum(x == "Movie"), # Set to FALSE for ascending order .desc = TRUE ), fill = type ) ) + geom_bar(position = "dodge") + coord_flip()
This achieves the same result but condenses the sorting logic into the aes() mapping.
Either approach will reorder your horizontal bars so that the year with the most movies sits at the top (after coord_flip()), and the year with the fewest sits at the bottom.
内容的提问来源于stack exchange,提问作者Ridwan Adejumo Suleiman

