考虑以下代码,它应该制作两个相同的条形图(轴标签除外)。 data.frame
dat
代表我拥有的数据类型,只是颜色响应。在绘图中使用这些颜色似乎是个好主意。
colOrder = c('green', 'blue', 'red', 'orange', 'purple')
dat <- data.frame(q = rep(c('red', 'orange', 'green', 'blue', 'purple'), c(1:5)))
# using geom_bar
ggplot(dat, aes(x = factor(q, levels = colOrder) )) +
geom_bar(fill = colOrder)
#using geom_col
dc <- as.data.frame(table(dat$q))
names(dc) <- c('q', 'n')
ggplot(dc, aes(x = factor(q, levels = colOrder), y = n )) +
geom_col(fill = colOrder)
为什么这些图不相同?
geom_col
似乎是使用 dc$q
中的颜色顺序填充的,而 geom_bar 根据要求正确采用了 colOrder
。我是否遗漏了 geom_col
文档中的某些内容?错误?
问题在于您将填充颜色作为参数传递给
geom_bar/col
。这样做时,颜色会根据 geom_bar/col
使用的数据集中出现的顺序分配给类别。虽然 geom_col
按原样使用数据,但 geom_bar
首先通过 stat="count"
计算计数,并根据 x
上映射的变量对数据重新排序。因此,当将填充颜色向量添加到这些数据集时,某些类别会得到不同的颜色。
您可以通过使用
layer_data()
清楚地看到这一点,它允许检索引擎盖下 geom
层使用的数据:
colOrder = c('green', 'blue', 'red', 'orange', 'purple')
dat <- data.frame(q = rep(c('red', 'orange', 'green', 'blue', 'purple'), 1:5))
library(ggplot2)
p1 <- ggplot(dat, aes(x = factor(q, levels = colOrder) )) +
geom_bar(fill = colOrder)
dc <- as.data.frame(table(dat$q))
names(dc) <- c('q', 'n')
p2 <- ggplot(dc, aes(x = factor(q, levels = colOrder), y = n )) +
geom_col(fill = colOrder)
layer_data(p1, 1)[c("x", "y", "group", "fill")]
#> x y group fill
#> 1 1 3 1 green
#> 2 2 4 2 blue
#> 3 3 1 3 red
#> 4 4 2 4 orange
#> 5 5 5 5 purple
layer_data(p2, 1)[c("x", "y", "group", "fill")]
#> x y group fill
#> 1 2 4 2 green
#> 2 1 3 1 blue
#> 3 4 2 4 red
#> 4 5 5 5 orange
#> 5 3 1 3 purple
很明显,对于
geom_bar
又名第一个图,数据在统计转换后根据 colOrder
进行排序,而对于 geom_col
又名第二个图,数据未重新排序。
如果您想要相同或一致的颜色,请映射
fill
美学并通过scale_fill_manual
设置颜色:
p3 <- ggplot(dat, aes(x = factor(q, levels = colOrder) )) +
geom_bar(aes(fill = q)) +
scale_fill_manual(values = colOrder)
p4 <- ggplot(dc, aes(x = factor(q, levels = colOrder), y = n )) +
geom_col(aes(fill = q)) +
scale_fill_manual(values = colOrder)
library(patchwork)
(p1 + p2) / (p3 + p4)