'How to use specific years to analysis?

I want to use specific 3 years to analysis, so I create a vector "score_3y". When I use "score1" only, it display correctly. When I use score1_3y, it display nothing, and shows:

Error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (54): x
Run `rlang::last_error()` to see where the error occurred.
Warning message:
`guides(<scale> = FALSE)` is deprecated. Please use `guides(<scale> = "none")` instead. 

What is the problem? Here is the code:

score1_3y <- score1[year == 2020 | year == 2021 | year == 2022]
ggplot(kaoyan, aes(score1_3y, fill = major))+
  geom_density(alpha = 0.6)+
  facet_wrap(~major)

str(kaoyan)
tibble [54 x 11] (S3: tbl_df/tbl/data.frame)
 $ college   : chr [1:54] "SUDA" "SUDA" "SUDA" "SUDA" ...
 $ applicants: num [1:54] 87 87 87 87 87 87 87 87 87 87 ...
 $ admission : num [1:54] 11 11 11 11 11 11 11 11 11 11 ...
 $ ratio     : num [1:54] 7.91 7.91 7.91 7.91 7.91 ...
 $ exemption : num [1:54] 3 3 3 3 3 3 3 3 3 3 ...
 $ major     : Factor w/ 2 levels "情报学","档案学": 1 1 1 1 1 1 1 2 2 2 ...
 $ year      : Factor w/ 5 levels "2018","2019",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ score1    : num [1:54] 416 410 377 358 358 364 344 403 400 406 ...
 $ score2    : num [1:54] 409 408 378 390 387 372 385 401 398 392 ...
 $ score3    : num [1:54] 825 818 755 748 745 736 729 804 798 798 ...
 $ gjx       : num [1:54] 341 341 341 341 341 341 341 341 341 341 ...
r


Solution 1:[1]

The reason is that we are using original dataset with the subset of rows object in aes, which obviously cause a length difference. Instead, just filter or subset the data and use 'score1'

library(dplyr)
library(ggplot2)
kaoyan %>%
   filter(year %in% 2020:2022) %>%
   ggplot(aes(score1, fill = major)) + 
     geom_density(alpha = 0.6) +
     facet_wrap(~major)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 akrun