我正在编写一个函数来为用户绘制热图。在下面的示例中,它绘制了不同性别的成绩随时间的变化。
然而,这是一个特例。 “性别”可能有其他名称,如“类”。 我将让用户输入他们的特定名称,然后让ggplot为每个轴都有正确的标签。
如何根据我的需要修改我的功能“heatmap()
”?
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)
heatmap=function(sampledata,Gender)
{
sampledata$Time <- factor(sampledata$Time)
sampledata$Grade <- factor(sampledata$Grade)
sampledata$Gender <- factor(sampledata$Gender)
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"))
}
答案 0 :(得分:2)
最简单的解决方案是使用aes_string重新定义函数。 调用该函数时,需要将其传递给列的名称 你想用作一个字符串。
heatmap=function(sampledata,y)
{
sampledata$Time <- factor(sampledata$Time)
sampledata$Grade <- factor(sampledata$Grade)
sampledata$new_var <- factor(sampledata[,y])
color_palette <- colorRampPalette(c("#31a354","#2c7fb8", "#fcbfb8","#f03b20"))(length((levels(factor(sampledata$Grade)))))
ggplot(data = sampledata) + geom_tile( aes_string(x = "Time", y = "new_var", 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")) + ylab(y)
}
# Below an example of how you call the newly defined function
heatmap(sampledata, "Gender")
或者,如果您想保留引用免费语法,则有一个稍微复杂的解决方案:
heatmap=function(sampledata,y)
{
arguments <- as.list(match.call())
axis_label <- deparse(substitute(y))
y = eval(arguments$y, sampledata)
sampledata$Time <- factor(sampledata$Time)
sampledata$Grade <- factor(sampledata$Grade)
sampledata$y <- factor(y)
color_palette <- colorRampPalette(c("#31a354","#2c7fb8", "#fcbfb8","#f03b20"))(length((levels(factor(sampledata$Grade)))))
ggplot(data = sampledata) + geom_tile( aes(x = Time, y = y, 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")) + ylab(axis_label)
}
# Below an example of how you call the newly defined function
heatmap(sampledata, Gender)