Hi, I'm trying to change the order of values on X axis of geom_col and by using factor() and scale_x_discrete() functions and it worked but and the same time the colour order changed.
colors <- c("#f2f0f7", "#dadaeb", "#bcbddc", "#9e9ac8", "#756bb1", "#54278f")
positions <- c("P1", "P8", "P3", "P4", "P5", "P6")
positions <- factor(positions, levels = c("P1", "P8", "P3", "P4", "P5", "P6")) # order on legend
ggplot() +
scale_x_discrete(limits = positions) +
geom_col(data=a, aes(x = X, y = M, fill = positions), width = 0.75, position = position_dodge(0.1), colour = "black", size = 0.9) +
labs(title = paste(Rname, Tname, sep = " ")) + xlab(Rname) + ylab(Tname) +
coord_cartesian(ylim = c(0, NA)) +
geom_errorbar(data=a, aes(x = X, y = M, ymin = M, ymax = max), width=0.5, size=1) +
scale_fill_manual(values = colors, breaks = positions) +
scale_y_continuous(expand=c(0,0), limits = c(0,max(df2$Y, na.rm = TRUE)*1.05)) +
theme_set(theme_classic(base_size = 30, base_family = "Helvetica", base_line_size = 1)) +
theme(
aspect.ratio = 5/4,
axis.line.y.left = element_line(),
axis.text = element_text(hjust = 1, color = "black"),
axis.text.x = element_text(angle=45),
axis.text.y = element_text(angle=0),
axis.title.x.bottom = element_text(size = 22, angle=0, margin = margin(t=20)),
axis.title.y = element_text(size = 22, angle=0, margin = margin(r = 20), vjust = 0.5),
plot.title = element_text(size = 30, margin = margin(b = 30), hjust = 0.5 ),
axis.ticks.y = element_line(),
axis.ticks.length.y = unit(10,"pt"),
)
I managed to changed it back to normal by changing the order of colours in scale_fill_manual:
scale_fill_manual(values = c("#f2f0f7", "#bcbddc", "#9e9ac8", "#756bb1", "#54278f", "#dadaeb"), breaks = positions) +
but it messed up the legend colour order... Could you please guide me in the right direction where both the x axis and colour order are preserved on both plot and the legend?
The main error is to have two variables for the same x axis, X
and positions
. The graph only needs positions
.
I will focus on getting the colors in their right places, the other layers can then be added.
library(ggplot2)
ggplot(a, aes(positions, M, fill = positions)) +
geom_col(width = 0.75, position = position_dodge(0.1), colour = "black", size = 0.9) +
scale_x_discrete(limits = positions) +
coord_cartesian(ylim = c(0, NA)) +
scale_fill_manual(values = colors, breaks = positions) +
theme_bw()
Data
set.seed(2020) # needed to make the y axis values reproducible
colors <- c("#f2f0f7", "#dadaeb", "#bcbddc", "#9e9ac8", "#756bb1", "#54278f")
positions <- c("P1", "P8", "P3", "P4", "P5", "P6")
positions <- factor(positions, levels = c("P1", "P8", "P3", "P4", "P5", "P6")) # order on legend
M <- sample(10, length(positions), TRUE)
a <- data.frame(M, positions, colors)
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.