首页 > 解决方案 > 如何在 geom_col 上订购颜色填充?

问题描述

第一个情节

嗨,我正在尝试通过使用 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"), 
  )

第二个情节

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

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

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

第三个情节

标签: rggplot2

解决方案


主要错误是对于同一个 x 轴有两个变量,X并且positions. 该图只需要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()

在此处输入图像描述

数据

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)

推荐阅读