I have a question regarding ggplot diagram that i cant solve, my struggle comes from the fact that i have to put multiple variables on the X axis and that I have to take the values for 2 different data frame.
Assume i am given the following 2 data frames:
Question<-c(1,2,3)
True<-c(30,20,10)
False<-c(10,15,20)
None<-c(3,2,3)
df1<-data.frame(Question, True, False, None)
Question<-c(1,2,3)
True<-c(20,20,15)
False<-c(20,15,5)
None<-c(3,2,2)
df2<-data.frame(Question, True, False, None)
df1 would look like this
Question True False None
1 30 10 3
2 20 15 2
3 15 5 2
And df2 would look similar
It is asked that i produce side by side chart comparing the distribution on df1 versus df2 for each question using a facet ggplot.
This plot needs to specifically look like this where Group 1 is from df1 and group 2 is from df2:
Thank you all
I would suggest this approach. With your dataframes you can create the Group
variable, bind the data with rbind()
and then reshape to have the desired variables in a format ready for the plot:
library(tidyverse)
#Data
Question<-c(1,2,3)
True<-c(30,20,10)
False<-c(10,15,20)
None<-c(3,2,3)
df1<-data.frame(Question, True, False, None)
#Data 2
Question<-c(1,2,3)
True<-c(20,20,15)
False<-c(20,15,5)
None<-c(3,2,2)
df2<-data.frame(Question, True, False, None)
#Bind data
df1$Group <- 'df1'
df2$Group <- 'df2'
dfg <- rbind(df1,df2)
#Reshape
dfg %>% pivot_longer(cols = -c(Question,Group)) %>%
ggplot(aes(x=name,y=value,fill=Group))+
geom_bar(stat = 'identity',position = position_dodge(0.9))+
facet_wrap(.~Question)
Output:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.