I can't seem to get around this error where it says the aesthetics must either be length 1 or the same as the data, which in my case is 368.
I have created two variables from the data, both of which are 18 values. These are my x and y values, where the x axis is the year, and the y axis is the vote share of radical right candidates in those years. My variables are the same length, so why is this error occurring and how do I correct this?
austria_year <- elect$year[26:43]
ggplot(data=elect, aes(x=austria_year, y=austria_rad_right)) +
geom_line() +
xlab("Year") +
ylab("Radical Right Vote Share") +
ggtitle("Austria Radical Right Support Over Time") +
theme_gray() +
theme(panel.grid=element_blank())
If you subset anything, subset everything.
ggplot(data = elect[26:43,], aes(x = year, y = austria_rad_right)) +
geom_line() +
xlab("Year") +
ylab("Radical Right Vote Share") +
ggtitle("Austria Radical Right Support Over Time") +
theme_gray() +
theme(panel.grid = element_blank())
What you're doing with your code of aes(x = austria_year, y = austria_rad_right)
is similar to plot(21:23, 1:10)
(which fails). Okay, so the first few points are 21,1
, 22,2
, and 23,3
, but what do ,4
, ,5
, and beyond pair with?
Occasionally there is a need to show different portions of the data in different layers. For instance, points from all data and lines from a subset. For that, we can take advantage of data=
arguments to individual layers.
ggplot(mtcars, aes(mpg, cyl)) +
geom_point() +
geom_path(data = ~ .[with(., ave(cyl, cyl, FUN = seq_along) < 2),],
color = "red")
I'm using the rlang
-style ~
tilde function, where the .
is replaced by the data provided in the main ggplot(.)
call. Why is this useful? Because often one can change the data in the first line and forget to update it in the remaining data-dependent layers; in this fashion, the subset of data used for the layer is dynamic.
This would apply to your case if you intend to show a layer from all data and then only a subset of it for another layer.
Perhaps this:
ggplot(data = elect, aes(x = year, y = austria_rad_right)) +
geom_point(color = "gray") +
geom_line(data = ~ .[26:43,]) +
xlab("Year") +
ylab("Radical Right Vote Share") +
ggtitle("Austria Radical Right Support Over Time") +
theme_gray() +
theme(panel.grid = element_blank())
Admittedly I'd prefer a better method of subsetting the data, perhaps something like
geom_line(data = ~ subset(., country == "Austria")) +