I'm having trouble making the charts in the order that appears in the axis.
I changed the levels of the factors in every possible way (relevel, level, ...). When I plot the main graphs, they are in the correct order, the labels are in the correct order too, but the boxplots are in the alphabetical order and the content of one main graph is switched with another (alphabetical order too).
The code below works well:
a <- ggplot(data, aes(x = GroupX, y = Score, fill=GroupX, order=GroupX))+
scale_fill_manual(values=colours) +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
legend.position="none",
panel.background = element_rect(fill = "white"),
panel.grid.major = element_line(colour = "gray95"),
panel.border = element_rect(fill = NA, colour = "black", size = 2))+
ylab("Lesion")+
xlab("")+
guides(colour=FALSE)+
facet_wrap(~ Portion)
The code below produces the correct facet:
When I try to plot with:
a + geom_boxplot()
The order of bars and the entire graph appears in the alphabetical order.
Levels are in the correct format. I can't figure how to correct this.
- Reproducible example
Dataset:
structure(list(Level = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c("A", "B", "C", "D", "E"
), class = "factor"), Factor = structure(c(1L, 1L, 3L, 3L, 2L,
2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L,
3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("X", "Y", "Z"
), class = "factor"), Valor = c(12, 11, 20, 15, 2, 5, 21, 21,
51, 1, 2, 15, 2, 56, 5, 21, 5, 12, 21, 15, 23, 5, 4, 55, 1, 2,
89, 2, 4, 12, 23, 10, 12, 51, 45, 2, 15, 32, 21, 15, 4, 5, 45,
45, 2, 14)), .Names = c("Level", "Factor", "Valor"), row.names = c(NA,
-46L), class = "data.frame")
Code without change the order:
a <- ggplot(data, aes(x = Level, y = Valor, fill=Factor, order=Level)) +
facet_wrap(~ Factor)
a + geom_boxplot()
When we set the factor - fast way:
levels(data$Factor) <- c("Y", "Z", "X")
levels(data$Level) <- c("D", "C", "A", "B", "E")
Labels changed, but the plot don't change.