如何在geom_col上订购颜色填充?

时间:2020-06-20 11:19:25

标签: r ggplot2

First plot

嗨, 我正在尝试通过使用factor()和scale_x_discrete()函数来更改geom_col的X轴上的值的顺序,并且可以工作,但同时颜色顺序也发生了变化。

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"), 
  )

Second plot

我设法通过更改scale_fill_manual中的颜色顺序将其恢复为正常:

scale_fill_manual(values = c("#f2f0f7", "#bcbddc", "#9e9ac8", "#756bb1", "#54278f", "#dadaeb"), breaks = positions) + 

但是它弄乱了图例的颜色顺序...请您指导我正确的方向,在图和图例上都保留x轴和颜色顺序吗?

Third plot

1 个答案:

答案 0 :(得分:1)

主要错误是在同一x轴上有两个变量Xpositions。该图只需要positions

我将重点放在正确的颜色上,然后可以添加其他层。

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()

enter image description here

数据

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)