简体   繁体   中英

ggplot in R - geom_tile with color-splitted tiles

Suppose I have a data where group1 and group2 both assign an integer value from 0 to 4 to the entities a,b,c,d,e, so:

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

I want to plot these values using geom_tile() from the ggplot package in R:

ggplot(data, aes(x=data_value, y=data_id)) + 
  geom_tile(aes(fill = data_group), width = 0.4, height = 0.8)

The graph looks like this:

在此处输入图像描述

My problem is that for entity c Group1 and Group2 both assign the same value 2, but the red tile is overlayed by the blue one. Ideally, I would like to have a splitted tile in this case, that is half-red, half-blue. Does anyone have an idea of how to do this?

Many thanks in advance!

I feel like this would be best approached by splitting the data into overlapping and non-overlapping sets, then plotting them with separate geom_tile commands:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM