I have some data from people (i.e. reading of e-books and printed books) that I want to plot with respect to 3 different categories (i.e. age, place of living, and social status) in the same graph because the comparison would be easier to see this way. I did a plot using the tool facet_grid
of ggplot2.
A code akin to the one I have is the following:
library(ggplot2)
F1 <- rep(c("F11","F12"),4)
F2 <- rep(c("F21","F22","F23","F24","F25","F26"),4)
F3 <- rep(c("F31","F32","F33","F34","F35","F36"),4)
R1 <- c(rep("R1",4),rep("R2",4))
R2 <- c(rep("R1",12),rep("R2",12))
R3 <- c(rep("R1",12),rep("R2",12))
YN1 <- rep(c(rep("Yes",2),rep("No",2)),2)
YN2 <- rep(c(rep("Yes",6),rep("No",6)),2)
YN3 <- rep(c(rep("Yes",6),rep("No",6)),2)
C <- c(rep("C3",8),rep("C2",24),rep("C1",24))
df1 <- data.frame(Fill=F1,R=R1,YN=YN1)
df2 <- data.frame(Fill=F2,R=R2,YN=YN2)
df3 <- data.frame(Fill=F3,R=R3,YN=YN3)
nums <- c(13.686722,6.246296,85.220158,83.702738,52.768593,44.885623,46.138288,45.063411,
12.448873,25.969226,17.290794,11.733145,8.288770,3.889354,84.722827,72.213003,
80.786696,86.643134,90.212283,95.047198,69.149769,53.831649,45.815887,44.073420,
43.501864,46.696141,28.021930,44.350581,52.261603,54.302859,54.999190,52.240411,
7.984016,13.276286,18.632469,24.995091,26.862302,24.478694,92.015984,86.723714,
81.367531,75.004909,73.137698,75.521306,49.535149,51.837543,56.646371,64.814451,
66.873589,69.809610,50.464851,48.162457,43.353629,35.185549,33.126411,30.190390)
df <- data.frame(C,rbind(df1,df2,df3),nums)
ggplot(df, aes(x=YN,y=nums,fill=factor(Fill,levels=c(c("F31","F32","F33","F34","F35","F36"),
c("F21","F22","F23","F24","F25","F26")
,c("F11","F12"))))) +
scale_fill_manual(values=c("#74ADD1","#ABD9E9", "#E0F3F8", "#D9EF8B","#A6D96A","#66BD63"
,rev(c("#8DD3C7","#FFFFB3","#BEBADA","#FB8072","#80B1D3","#FDB462")),
"#FBB4AE","#B3CDE3"))+
geom_bar(position=position_stack(reverse=F), stat="identity", colour="black",size=.3)+
facet_grid(C~R,scales="free") + labs(fill="Fill")
I'm new to this site so it doesn't let me add pictures, but the plot it generates is this one.
As you can see, there's three different groups of colours for the fillings of the bars, one for each category. However, the legend of said fillings displays them all as if they were one big group. This is what I'd like to change. I'd want to separate this legend in three groups, one corresponding to each category. I've edited the plot to show precisely what my aim is. The actual plot I would like to get is something similar to this one.
I'm not sure if something like it can be achieved with code, or if instead I may have to edit the original plot with some graphic design tool like I've done here haha.
I'm rather new to coding on R so any help would be greatly appreciated. Thanks in advance.