【发布时间】:2022-01-13 00:07:27
【问题描述】:
我正在构建一个仪表板,其中包含按访问者数量排名前 10 位的棒棒糖图表,按年份划分。这是我使用虚拟数据构建的大致相似的图:
要按每个方面的访问者总数重新排序位置,I used reorder_within() and scale_x_reorder(), created by Tyler Rinker。对于顺序调色板,我使用了 RColorBrewer 和 scale_color_distiller。
关于条形图的颜色,我想更改三件事,但我不确定如何更改。
- 我希望颜色从稍暗而不是接近白色开始,因为它们有点难以看到。
- 我希望每个条形图都有自己的颜色,即使访客人数相同,也希望这些颜色彼此清晰可辨,同时仍然是连续的。
- 我希望每个方面都具有相同的配色方案,以便看起来一致 - 我知道方案在各个方面有所不同,因为它们都有不同的访客人数。
下面带有一些虚拟数据的可重现示例:
library(tidyverse)
library(RColorBrewer)
#facet reorder code - by Tyler Rinker
reorder_within <-
function(x,
by,
within,
fun = mean,
sep = "___",
...) {
new_x <- paste(x, within, sep = sep)
stats::reorder(new_x, by, FUN = fun)
}
scale_x_reordered <- function(..., sep = "___") {
reg <- paste0(sep, ".+$")
ggplot2::scale_x_discrete(
labels = function(x)
gsub(reg, "", x),
...
)
}
dummy <- data.frame(
Year = rep(c(2019, 2020, 2021), c(10)),
Destination = c("loc_4322", "loc_43267", "loc_6786", "loc_43294", "loc_45566",
"loc_1234", "loc_367", "loc_14765", "loc_49865", "loc_90765",
"loc_4332", "loc_367", "loc_2112", "loc_596111", "loc_54980",
"loc_539", "loc_5699", "loc_1965", "loc_6387", "loc_213",
"loc_5245", "loc_4787", "loc_34098", "loc_67609", "loc_50954",
"loc_54421", "loc_548901", "loc_23245", "loc_4322", "loc_0986"),
Visitor_numbers = c(102234, 234984, 39546, 108943, 430985, 243056, 342890,
253980, 129803, 134954, 21954, 128904, 223242, 223242,
223242, 23242, 243980, 134324, 542323, 12545, 905334,
123434, 123434, 569085, 5085, 235463, 209384, 230923,
243089, 120923)
)
destinations <- dummy %>%
ggplot() +
(aes(
x = reorder_within(Destination, -Visitor_numbers, Year),
y = Visitor_numbers,
color = Visitor_numbers
)) +
geom_point(size = 4) +
geom_segment(
aes(
x = reorder_within(Destination, -Visitor_numbers, Year),
xend = reorder_within(Destination, -Visitor_numbers, Year),
y = 0,
yend = Visitor_numbers
),
size = 2
) +
scale_x_reordered() +
scale_color_distiller(type = "seq", palette = "Oranges", direction = 1) +
facet_wrap(~ Year,
dir = "v",
scales = "free",
ncol = 1) +
coord_flip()
destinations
非常感谢任何帮助。
【问题讨论】:
-
我不明白你的#3。在我看来,每个方面都具有相同的配色方案,并且它们看起来一致。您是说要在 #1 和 #2 的更改完成后保持该方面,还是说 #3 是我缺少的更改?
-
抱歉,也许我有点模棱两可。例如,我知道方面 3 中的最后一个条比其他条要暗得多,因为 loc_5245 中的访问者数量明显高于图中的任何其他位置。我只是希望颜色在所有 3 个方面看起来一致。我认为,如果其他条形之间的区别更明显,那就没那么重要了,因为否则你会有很多颜色几乎无法区分的条形,而只有 1 或 2 个非常暗的。
-
为简化起见,我只希望每个方面的每个条都具有可区分的不同颜色,同时仍与 Visitor_numbers 连续。
-
这些值的分布是什么?如果它是对数正态的,则将颜色映射到
log10(Visitor_number)可能更有意义 -
或者你只是想给集合中的每一行一个唯一的颜色,你可以将
color映射到seq_along(Destination)