R 中的 ggplot - geom_tile 带有分色图块
ggplot in R - geom_tile with color-splitted tiles
假设我有一个数据,其中 group1 和 group2 都将 0 到 4 的整数值分配给实体 a、b、c、d、e,所以:
data <- data.frame(data_id = c(letters[1:5], letters[1:5]), data_group = c(replicate(5, "Group1"), replicate(5, "Group2")), data_value = c(0:4, replicate(5,2)))
我想使用 R 中 ggplot 包中的 geom_tile()
绘制这些值:
ggplot(data, aes(x=data_value, y=data_id)) +
geom_tile(aes(fill = data_group), width = 0.4, height = 0.8)
图形如下所示:
我的问题是,对于实体 c Group1 和 Group2 都分配了相同的值 2,但红色图块被蓝色图块覆盖。理想情况下,我希望在这种情况下有一个分裂的瓷砖,即一半红色,一半蓝色。有没有人知道如何做到这一点?
非常感谢!
我觉得最好的方法是将数据分成重叠的 non-overlapping 组,然后用单独的 geom_tile
命令绘制它们:
library(dplyr)
data <- data.frame(data_id = c(letters[1:5],
letters[1:5]),
data_group = c(replicate(5, "Group1"),
replicate(5, "Group2")),
data_value = c(0:4, replicate(5,2)))
data_unique <- data %>% ## non-overlapping data
group_by(data_id, data_value) %>%
filter(n() == 1)
data_shared <- data %>% ## overlapping data
group_by(data_id, data_value) %>%
filter(n() != 1)
ggplot(data,
aes(x = data_value, y = data_id)) +
geom_tile(data = data_unique, aes(fill = data_group, group = data_group),
width = 0.4, height = 0.8) + ## non-overlapping data
geom_tile(data = data_shared, aes(fill = data_group, group = data_group),
width = 0.4, height = 0.8,
position = "dodge") ## non-overlapping data
假设我有一个数据,其中 group1 和 group2 都将 0 到 4 的整数值分配给实体 a、b、c、d、e,所以:
data <- data.frame(data_id = c(letters[1:5], letters[1:5]), data_group = c(replicate(5, "Group1"), replicate(5, "Group2")), data_value = c(0:4, replicate(5,2)))
我想使用 R 中 ggplot 包中的 geom_tile()
绘制这些值:
ggplot(data, aes(x=data_value, y=data_id)) +
geom_tile(aes(fill = data_group), width = 0.4, height = 0.8)
图形如下所示:
我的问题是,对于实体 c Group1 和 Group2 都分配了相同的值 2,但红色图块被蓝色图块覆盖。理想情况下,我希望在这种情况下有一个分裂的瓷砖,即一半红色,一半蓝色。有没有人知道如何做到这一点?
非常感谢!
我觉得最好的方法是将数据分成重叠的 non-overlapping 组,然后用单独的 geom_tile
命令绘制它们:
library(dplyr)
data <- data.frame(data_id = c(letters[1:5],
letters[1:5]),
data_group = c(replicate(5, "Group1"),
replicate(5, "Group2")),
data_value = c(0:4, replicate(5,2)))
data_unique <- data %>% ## non-overlapping data
group_by(data_id, data_value) %>%
filter(n() == 1)
data_shared <- data %>% ## overlapping data
group_by(data_id, data_value) %>%
filter(n() != 1)
ggplot(data,
aes(x = data_value, y = data_id)) +
geom_tile(data = data_unique, aes(fill = data_group, group = data_group),
width = 0.4, height = 0.8) + ## non-overlapping data
geom_tile(data = data_shared, aes(fill = data_group, group = data_group),
width = 0.4, height = 0.8,
position = "dodge") ## non-overlapping data