如何在ggplot geom_tile中固定/调整每个波段的宽度 [英] 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)
我正在使用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 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!
推荐答案
如果您希望宽度"相同,则可以在geom_tile
中使用height
美观度:
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))
如果希望它们独立,则需要传递与sampledata
data.frame
相同长度的向量,也许最简单的方法是创建一个新变量:
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)
然后:
ggplot(data = sampledata) +
geom_tile(aes(x = Time, y = Gender, fill = Grade, height = myHeight))
这篇关于如何在ggplot geom_tile中固定/调整每个波段的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!