Yukun
Yukun

Reputation: 325

How to fix/adjust the width of each band in ggplot geom_tile

Here is a sample data for my question:

sampledata <- matrix(c(1:60,1:60,rep(0:1,each=60),sample(1:3,120,replace = T)),ncol=3)
colnames(sampledata) <- c("Time","Gender","Grade")
sampledata <- data.frame(sampledata)
sampledata$Time <- factor(sampledata$Time)
sampledata$Grade <- factor(sampledata$Grade)
sampledata$Gender <- factor(sampledata$Gender)

I am plotting an heatmap from this sample data using geom_tile

color_palette <- colorRampPalette(c("#31a354","#2c7fb8", "#fcbfb8", "#f03b20"))(length((levels(factor(sampledata$Grade)))))
ggplot(data = sampledata) + geom_tile( aes(x = Time, y = Gender, fill = Grade))+scale_x_discrete(breaks = c("10","20","30","40","50"))+scale_fill_manual(values =color_palette,labels=c("0-1","1-2","2-3","3-4","4-5","5-6",">6"))+  theme_bw()+scale_y_discrete(labels=c("Female","Male"))

I got this graph: enter image description here

I want to adjust the width of Male and Female separately so that I get different widths for different gender.The meaning of width is shown in the following pic: enter image description here

Is it possible to do this by making changes to my current code? Thanks!

Upvotes: 4

Views: 3574

Answers (1)

JasonAizkalns
JasonAizkalns

Reputation: 20473

If you want the "widths" to be the same, you can use the height aesthetic within geom_tile:

ggplot(data = sampledata) +
    geom_tile(aes(x = Time, y = Gender, fill = Grade, height = 0.25))

Plot 01

If you want them to be independent, then you need to pass a vector of the same length of the sampledata data.frame, perhaps the easiest approach is to create a new variable:

# Assign Females a height of 0.25 and Males a height of 0.75
sampledata$myHeight = ifelse(sampledata$Gender == 0, 0.25, 0.75)

And then:

ggplot(data = sampledata) + 
  geom_tile(aes(x = Time, y = Gender, fill = Grade, height = myHeight)) 

Plot 02

Upvotes: 3

Related Questions