Reputation: 51
I have a data in the below format
occupation,how_many_happy, how_many_not_happy
Teacher, 50, 30
I am trying to plot a histogram by using both how_many_happy
, how_many_not_happy
on the x axis for each occupation separatly using ggplot as below
ggplot(Occupations_vs_parties,
aes(x = c(Occupations_vs_parties$How_many_happy,
Occupations_vs_parties$How_many_not_happy))) +
facet_wrap(~Occupation, nrow = 4)
However I am getting the error as below
Error: Aesthetics must be either length 1 or the same as the data (17): x
Can you please help me with the way forward. Please let me know if any inputs are needed
Thanks, Surya
Upvotes: 0
Views: 37
Reputation: 50718
There are quite a few mistakes in your code. Most fundamentally, I would recommend reading up on (1) converting data from wide to long format, and (2) general ggplot
syntax, especially the use of geom_histogram
and geom_bar
(for example you don't actually specify how you want to plot your data).
With the sample data that you give, there is also no point in facet wrapping occupation
. So your example data might not be a representative minimal example.
Here is an simple barplot based on your sample data.
# Sample data
df <- read.csv(text =
"occupation,how_many_happy,how_many_not_happy
Teacher,50,30", sep = ",");
# Convert wide to long dataframe
library(reshape2);
df.long <- melt(df);
# (gg)plot
require(ggplot2);
ggplot(df.long, aes(x = variable, y = value)) + geom_bar(stat = "identity"),
If you do have different occupation
levels, you can add ... + facet_wrap(~ occuptation)
to your ggplot
command.
Upvotes: 1