如何修复/调整 ggplot geom_tile 中每个带的宽度

2024-03-28

这是我的问题的示例数据:

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)

我正在使用此示例数据绘制热图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

是否可以通过更改我当前的代码来做到这一点?谢谢!


如果您希望“宽度”相同,可以使用height内在的审美geom_tile:

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

如果你希望它们是独立的,那么你需要传递一个与sampledata data.frame,也许最简单的方法是创建一个新变量:

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

进而:

ggplot(data = sampledata) + 
  geom_tile(aes(x = Time, y = Gender, fill = Grade, height = myHeight)) 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何修复/调整 ggplot geom_tile 中每个带的宽度 的相关文章

随机推荐