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

旧街凉风 提交于 2019-12-07 15:38:04

问题


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:

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:

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


回答1:


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

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



来源:https://stackoverflow.com/questions/37443499/how-to-fix-adjust-the-width-of-each-band-in-ggplot-geom-tile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!