我的问题类似于this one,但我不能让这个答案适用于我的情节。
我正在使用geom_linerange
为一组名称(1:20
)制作时间表,每个名称都与赞助商(B:E
)相关联。我想“面对”图表,以便名称/时间线按赞助商分组。到目前为止,如果我创建一个包含赞助商+名称的“组合”因子,我可以得到一个组合图。但是,如果我尝试分面,那么每个赞助商都会所有名称。
以下是我的数据集(已修改的子集)(我使用lubridate
作为日期...):
structure(list(Sponsor = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("B",
"C", "D", "E"), class = "factor"), Last = structure(1:20, .Label = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20"), class = "factor"),
Grant = c(0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5,
0, 1, 1, 0), Start = structure(c(844128000, 904003200, 1001289600,
1314835200, 1064188800, 1107561600, 1138838400, 1264896000,
1222819200, 1042502400, 1343779200, 904521600, 950832000,
1009929600, 1081209600, 1171929600, 821664000, 865209600,
979603200, 1209600000), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
End = structure(c(929232000, 946684800, 1088035200, NA, 1109721600,
1324512000, 1232496000, NA, NA, 1101859200, 1388448000, 993859200,
1006819200, 1103500800, 1139529600, 1235952000, 919036800,
1030665600, 1047254400, 1272585600), class = c("POSIXct",
"POSIXt"), tzone = "UTC"), Combo = c("B_1", "B_2", "B_3",
"B_4", "B_5", "B_6", "B_7", "B_8", "C_9", "C_10", "C_11",
"D_12", "D_13", "D_14", "D_15", "D_16", "E_17", "E_18", "E_19",
"E_20")), .Names = c("Sponsor", "Last", "Grant", "Start",
"End", "Combo"), row.names = c(NA, 20L), class = "data.frame")
这是生成非分面图的命令,该图按顺序对事物进行分组,但不进行细分:
library(ggplot2)
require(lubridate)
YearLine = ymd(19960101) + years(seq(0,18))
ggplot(testdat,aes(Combo, Start, ymin=Start,ymax=End,color=as.factor(Grant),xticks)) + xlab("Sponsor") + geom_linerange(size=4,alpha=.7) + geom_point(size=4,shape=18) + coord_flip() + scale_colour_brewer(palette="Spectral") + scale_x_discrete(labels=testdat$Sponsor) + geom_hline(yintercept = as.numeric(YearLine),alpha=0.6,col="indianred1",linetype="dotted") + annotate("text", x = testdat$Combo, y = testdat$Start, label = testdat$Last, hjust=0,size=2.5)
这是产生的情节。这是我想要的(因为它不是多余的),但我希望它由赞助商细分:
如果我添加+ facet_grid(Sponsor ~ .,scale="free_x",space="free_x")
(或free_y
),那么赞助商就会按照我的希望来面对这些小组,但我仍然会列出所有名单,即使它们与此无关“赞助商“B到E:
答案 0 :(得分:1)
您遇到的主要问题是使用annotate
,您需要使用geom_text
:
ggplot(testdat,aes(Combo, Start, ymin=Start,ymax=End,color=as.factor(Grant),xticks)) +
xlab("Sponsor") + geom_linerange(size=4,alpha=.7) + geom_point(size=4,shape=18) + coord_flip() +
scale_colour_brewer(palette="Spectral") +
scale_x_discrete(labels=testdat$Sponsor) +
geom_hline(yintercept = as.numeric(YearLine),alpha=0.6,col="indianred1",linetype="dotted") +
geom_text(aes(x=Combo, y=Start, label = testdat$Last), colour="black") +
facet_grid(Sponsor ~ .,scale="free_x",space="free_x")
annotate
并没有真正遵循你为其余情节定义的现有美学映射,这就是为什么它不受你的刻面影响。