Reputation: 304
R and ggplot newbie here. I'm trying to create some meaningful plots for a data frame representing answers to a questionnaire in which some people gave multiple answers of the sort:
what meat do you like (check all that apply): 1.fish; 2.pork
for other questions there's only one choice:
do you drink beer? seldom / often / never
Since there are multiple answers, they have been coded as dummy variables: eat.fish has value 1 for a positive answer, 0 otherwise and the same for eat.pork. The data frame looks like this:
pork<-c(0,1,0,1,1)
id<-c(1:5)
sex<-c("m","m","f","f","f")
eat.fish<-c(1,1,0,0,1)
eat.pork<-c(0,1,0,1,1)
drink.beer<-c("often","seldom","never","seldom","never")
df<-data.frame(id,sex,eat.fish,eat.pork,drink.beer)
Now, for a categorical variable like drink.beer, I know how to get some meaningful plots with ggplot2:
qplot(data=df, drink.beer, fill=drink.beer)
and
qplot(data=df, drink.beer, fill=drink.beer)+facet_wrap(~sex)
but I would like to to the same for the pork and fish variables but I have no clue where to start.
Upvotes: 0
Views: 1989
Reputation: 83255
Now your eat.pork
and eat.fish
variables are numeric. You can convert them to factor variables inside the qplot
function like this:
qplot(data=df, as.factor(eat.pork), fill=as.factor(eat.pork)) + facet_wrap(~sex)
You can do the same for the eat.fish
variable. When you want to combine the eat.pork
and eat.fish
variables into one variable, see the answer of matt_k for an instruction how to do this.
Upvotes: 0
Reputation: 4489
You could recode the variables
df$eat.pork2 <- ifelse(df$eat.pork == 1, "eat_pork", "dont_eat_pork")
qplot(data=df, eat.pork2, fill=eat.pork2)
Or if you want to combine pork and fish into a single variable
df$eat <- ifelse(df$eat.pork == 1 & df$eat.fish == 1, "eat_pork_fish",
ifelse( df$eat.pork == 1 & df$eat.fish == 0, "eat_pork_only",
ifelse( df$eat.pork == 0 & df$eat.fish == 1, "eat_fish_only",
"neither_pork_fish")))
qplot(data=df, eat, fill=eat)+facet_wrap(~sex)
qplot(data=df, eat, fill=eat)
Upvotes: 1