2016-07-26 81 views
1

我最近看到了一张我想在R中复制的图表。图表显示了一个彩色框的多个记录的分数或其他度量值,它被分成4种颜色之一。在我的形象中,它是红色,浅红色,浅绿色和绿色。因此,每个记录对于每个得分都会得到一个盒子 - 这个想法是,每个记录在几个时间点上对于给定时间点都有一个分数。在我的例子中,随着时间的推移,我将使用学生考试成绩,所以说我们全年有4名学生和8次考试(按照时间顺序),我们每个学生将有8个考试成绩,共32盒。每行(学生)将有8个盒子。使用ggplot复制趋势图

hacked-up attempt of the chart

这是我如何创建一些示例数据:

totallynotrealdata <- data.frame(Student = c(rep("A",8),rep("B",8),rep("C",8),rep("D",8)),Test = rep(1:8,4), Score = sample(1:99,32,replace = TRUE), BinnedScore = cut(totallynotrealdata$TB,breaks = c(0,25,50,75,100),labels = c(1,2,3,4))) 

什么我不知道是我怎么可以重新在这张图表中ggplot?我应该看的任何几何?

回答

1

你可以玩geom_rect()。这是很基本的,但我想你可以很容易地优化它为您的目的:

df <- data.frame(Student = c(rep(1,8),rep(2,8),rep(3,8),rep(4,8)), 
       Test = rep(1:8,4), 
       Score = sample(1:99,32,replace = TRUE)) 

df$BinnedScore <- cut(df$Score,breaks = c(0,25,50,75,100),labels = c(1,2,3,4)) 
df$Student  <- factor(df$Student, labels = LETTERS[1:length(unique(df$Student))]) 

library(ggplot2) 

colors <- c("#f23d2e", "#e39e9c", "#bbd3a8", "#68f200")  
numStuds <- length(levels(df$Student)) 
numTests <- max(df$Test) 

ggplot() + geom_rect(data = df, aes(xmin = Test-1, xmax = Test, ymin = as.numeric(Student)-1, ymax = as.numeric(Student)), fill = colors[df$BinnedScore], col = grey(0.5)) + 
    xlab("Test") + ylab("Student") + 
    scale_y_continuous(breaks = seq(0.5, numStuds, 1), labels = levels(df$Student)) + 
    scale_x_continuous(breaks = seq(0.5, numTests, 1), labels = 1:numTests) 

enter image description here

+0

我一直在寻找在geom_rect(),但ggplot功能下做的审美映射,而不是GEOM功能!我将不得不多玩一些 – user2784067

+0

顺便说一句,你的最终结果是非常令人满意的! – user2784067