【发布时间】:2016-06-21 18:19:45
【问题描述】:
我正在编写一个函数来为用户绘制热图。在以下示例中,它绘制了不同性别的成绩随时间的变化。
但是,这是一种特殊情况。 “性别”可能有其他名称,如“类”。 我会让用户输入他们的具体名称,然后让 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"))
}
【问题讨论】: