Reputation: 77
I have been trying to get ggplot in R to map 2 variables side by side in a bar plot against a catergorical Y Value
The data I have been using is the build in mpg in the "carat" Package.
However every time I run my code( which is listed below)
I receive the errorError: Aesthetics must be either length 1 or the same as the data (234): y
my code is :
ggplot(mpg,aes(x=fl,y=c(cty,hwy)))+
geom_bar()
Can someone please help To summarise I am using the MPG dataset in R and I'm trying to plot cty and why side by side in a barplot against their fuel type(fl)
Upvotes: 0
Views: 1170
Reputation: 417
Barcharts makes the height of the bar proportional to the number of cases in each group. It can't have x and y aesthetic at the same time.
From your description I think you want to map categorical data to numeric, in this case use boxplots e.g.
mpg %>%
select(fl, cty, hwy) %>%
pivot_longer(-fl) %>%
ggplot(aes(x = fl, y = value, fill = name)) + geom_boxplot()
Upvotes: 0
Reputation: 12719
One way to do this is to put the data into long format. Not really sure how meaningful this graph is as it gives the sum highway and city miles per gallon. Might be more meaningful to calculate the average highway and city miles per gallon for the different fuel types.
library(ggplot2)
library(tidyr)
mpg %>%
pivot_longer(c(cty,hwy)) %>%
ggplot(aes(x = fl, y=value, fill = name))+
geom_col(position = "dodge")
Created on 2021-04-10 by the reprex package (v2.0.0)
Upvotes: 1