Reputation: 115
I am trying to plot a bar chart with a gradient that goes from yellow to red. However, I keep getting "Error: Aesthetics must be either length 1 or the same as the data (10): y and fill".
This code worked perfectly with a nearly identical data frame, so I don't understand what I'm doing wrong. On another website they suggested picking the filling of each bar manually, i.e. fill=c("red", "...",) etc, but that would go against the idea of using a gradient.
Here's the code, below you can find a dput of the data frame if it helps:
Code:
plot <- df %>%
mutate(name1 = "Average unemployment rate") %>%
ggplot(aes(x=Region,
y=Avg_Unemployment_rate,
fill=Avg_Unemployment_rate)) +
geom_bar(stat='identity', show.legend=FALSE) +
scale_fill_gradient(low="yellow", high = "red") +
labs(y = "Unemployment Rate (%)", x="") +
theme(axis.text.x=element_text(angle =- 90, vjust = 0.5)) +
facet_wrap(~name1) +
coord_cartesian(ylim=c(0,6), expand=0)
dput
structure(list(Region = structure(c(10L, 1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L), .Label = c("South East", "South West", "London",
"East of England", "East Midlands", "West Midlands", "Yorkshire and The Humber",
"North East", "North West", "England"), class = "factor"), Avg_Unemployment_rate = structure(c(4.05052633258656,
3.21824018447441, 3.05119829228833, 4.7077689256265, 3.44297331188711,
4.23448912295878, 4.67588411516106, 4.45220611226308, 5.69591652090698,
4.06868093338517, 0.325604322866634, 0.36720756911479, 0.595564571651833,
0.538576162975837, 0.467897513070492, 0.427419900308709, 0.378156613118954,
0.469553277333867, 0.537080804732578, 0.33118433822167), .Dim = c(10L,
2L), .Dimnames = list(NULL, c("mean", "sd"))), SD = c(0.325604322866634,
0.36720756911479, 0.595564571651833, 0.538576162975837, 0.467897513070492,
0.427419900308709, 0.378156613118954, 0.469553277333867, 0.537080804732578,
0.33118433822167)), row.names = c(NA, -10L), class = "data.frame")
Thanks in advance!
EDIT: Duck's output
Upvotes: 2
Views: 119
Reputation: 39595
Try this:
library(ggplot2)
#Data
df <- cbind(df[,c(1,3)],df$Avg_Unemployment_rate)
#Plot
df %>%
mutate(name1 = "Average unemployment rate") %>%
ggplot(aes(x=Region,
y=mean,
fill=mean)) +
geom_bar(stat='identity', show.legend=FALSE) +
scale_fill_gradient(low="yellow", high = "red") +
labs(y = "Unemployment Rate (%)", x="") +
theme(axis.text.x=element_text(angle =- 90, vjust = 0.5)) +
facet_wrap(~name1) +
coord_cartesian(ylim=c(0,6), expand=0)
Output:
Upvotes: 2