r - geom_text() 在因子排序后删除数据
问题描述
我正在使用 geom_segment(R 新手)创建甘特图/时间线。
这段代码:
timeline <- ggplot(db, aes(x=Discovery.date, y=Compound.name, label=Compound.name, colour=Compound.name))+
geom_segment(aes(xend= End.Date, y=Compound.name, yend= Compound.name), size=5)+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_text(hjust = 'middle', nudge_x = 6, nudge_y= 0.11, colour="black")+
labs(x= "Discovery Date",
y= "Compound Name")+
theme(axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
legend.position="none")+
timeline
返回此图: 错误的顺序
当我使用此代码更改订单以反映发现日期时:
db$Compound.name <- factor(db$Compound.name, levels = c("sarkomycin",
"carzinophilin",
"mitomycin C",
"streptozocin",
"chromomycin A3",
"mithramycin",
"bleomycin",
"actinomycin D",
"doxorubicin",
"daunorubicin",
"zinostatin",
"aclarubicin",
"peplomycin",
"epirubicin HCl",
"pirarubicin",
"idarubicin HCl",
"pentostatin",
"zinostatin stimalamer",
"valrubicin",
"amrubicin HCl",
"temsirolimus"))
db$Compound.name <- factor(db$Compound.name, levels=rev(levels(db$Compound.name)))
结果: 正确的顺序 这会改变顺序,但会丢失 Compound.name= pirarubicin(y=从顶部开始的第 7 个)并且它变成顶部的灰色段。给出的理由:
删除了 1 行包含缺失值 (geom_text)
只有数据的顺序发生了变化,并且在 xlim 内。
任何帮助或建议将不胜感激。
示例代码:
Compound.name <- c("sarkomycin",
"carzinophilin",
"mitomycin C",
"streptozocin",
"chromomycin A3",
"mithramycin",
"bleomycin",
"actinomycin D",
"doxorubicin",
"daunorubicin",
"zinostatin",
"aclarubicin",
"peplomycin",
"epirubicin HCl",
"pirarubicin",
"idarubicin HCl",
"pentostatin",
"zinostatin stimalamer",
"valrubicin",
"amrubicin HCl",
"temsirolimus")
Discovery.date <- c("1954",
"1956",
"1958",
"1960",
"1961",
"1961",
"1962",
"1964",
"1972",
"1975",
"1976",
"1981",
"1981",
"1984",
"1988",
"1990",
"1992",
"1994",
"1999",
"2002",
"2007")
End.Date <- c("1965",
"1970",
"2018",
"2018",
"1960",
"2000",
"2018",
"2018",
"2018",
"2018",
"1985",
"2018",
"2018",
"2018",
"2018",
"2018",
"2018",
"2018",
"2018",
"2018",
"2018")
df<- data.frame(Compound.name, Discovery.date, End.Date)
解决方案
将label
论点从ggplot
美学 ( aes
) 移到geom_text
美学中。(我还把你所有的主题论点都移到了一个块中,只是为了更容易阅读)。
ggplot(df, aes(x=Discovery.date, y=Compound.name, colour=Compound.name))+ # OUT OF HERE
geom_segment(aes(xend= End.Date, y=Compound.name, yend= Compound.name), size=5)+
geom_text(aes(label=Compound.name), # INTO HERE
hjust = 'middle', nudge_x = 6, nudge_y= 0.11, colour="black")+
labs(x= "Discovery Date", y= "Compound Name")+
theme(axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
legend.position="none",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())