我正在使用热图来跟踪实验中的损耗,并且我想在前两列中专门打印一些日期信息,但由于某种原因,ggplot2 不会接受那么多缺失的观察结果。
这就是我目前的情节(许多日期的方式)。
谁能告诉我如何将 geom_text 限制为仅前两列?
有关示例代码,请参阅打击。
require(ggplot2)
require(plyr)
require(reshape)
# create sample data
set.seed(666)
dfn <- data.frame(
Referral = seq(as.Date("2007-01-15"), len= 26, by="23 day"),
VISIT01 = seq(as.Date("2008-06-15"), len= 24, by="15 day")[sample(30, 26)],
VISIT02 = seq(as.Date("2008-12-15"), len= 24, by="15 day")[sample(30, 26)],
VISIT03 = seq(as.Date("2009-01-01"), len= 24, by="15 day")[sample(30, 26)],
VISIT04 = seq(as.Date("2009-03-30"), len= 24, by="60 day")[sample(30, 26)],
VISIT05 = seq(as.Date("2010-11-30"), len= 24, by="6 day")[sample(30, 26)],
VISIT06 = seq(as.Date("2011-01-30"), len= 24, by="6 day")[sample(30, 26)],
Discharge = seq(as.Date("2012-03-30"), len= 24, by="30 day")[sample(30, 26)],
Patient = factor(1:26, labels = LETTERS),
openCase = rep(0:1, 100)[sample(100, 26)])
# set today's data for cases that do not have an Discharge date
dfn$Discharge[ is.na(dfn$Discharge) ] <- as.Date("2014-01-30")
mdfn <- melt(dfn, id=c('Patient', 'openCase'), variable_name = "Visit")
names(mdfn)[4] <- 'Year'
# order data in mdfn by 'Referral' in dfn
mdfn$Patient <- factor(mdfn$Patient,levels = (dfn$Patient[order(dfn$Referral)]),
ordered = TRUE)
mdfn$Year2 <- ifelse(mdfn$Year != 0, 1, 0)
mdfn$Year2[ is.na(mdfn$Year) ] <- 0
mdfn$FWrap <- 'Core Measures'
mdfn$FWrap[mdfn$Visit == 'Referral'] <- 'Referral'
mdfn$FWrap[mdfn$Visit == 'VISIT05' | mdfn$Visit == 'VISIT06'] <- 'Optional Measures'
mdfn$FWrap[mdfn$Visit == 'Discharge'] <- 'Discharge'
mdfn$FWrap <- ordered(mdfn$FWrap, levels = c('Referral', 'Core Measures', 'Optional Measures', 'Discharge'))
base_size <- 9
m2 <- ggplot(mdfn, aes(Visit, Patient)) +
geom_tile(aes(fill = Year2), colour = "gray") +
scale_fill_gradient(low = "white", high = "steelblue")
m2 + theme_grey(base_size = base_size) + labs(x = "", y = "") +
scale_x_discrete(expand = c (0, 0)) + scale_y_discrete(expand = c(0, 0)) +
opts(legend.position = "none", axis.ticks = theme_blank(),
axis.text.x = theme_text(size = base_size * 0.8, angle = 330, hjust = 0,
colour = "grey50")) + facet_grid(~ FWrap, scales = "free", space="free") +
geom_text(aes (label=format(Year, "%b. %d, %Y")), size=3, colour='white')
# this is how I thought I could solve it.
mdfn$Yearlabel <- mdfn$Year
mdfn$Yearlabel[mdfn$Visit != 'Referral' & mdfn$Visit != 'VISIT01'] <- NA
# mdfn[,c(4,5,7,3)]
m2 <- ggplot(mdfn, aes(Visit, Patient)) +
geom_tile(aes(fill = Year2), colour = "gray") +
scale_fill_gradient(low = "white", high = "steelblue")
m2 + theme_grey(base_size = base_size) + labs(x = "", y = "") +
scale_x_discrete(expand = c (0, 0)) + scale_y_discrete(expand = c(0, 0)) +
opts(legend.position = "none", axis.ticks = theme_blank(),
axis.text.x = theme_text(size = base_size * 0.8, angle = 330, hjust = 0,
colour = "grey50")) + facet_grid(~ FWrap, scales = "free", space="free") +
geom_text(aes (label=format(Yearlabel, "%b. %d, %Y")), size=3, colour='white')