躲避离散y值,geom_segment()

时间:2016-07-02 13:10:16

标签: r ggplot2

这是我可重复的例子:

IND.factions <- rbind(c("Mughal Empire", "IND", "1526-1-1", "1857-1-1", "IND"),
                  c("Maratha Empire", "IND", "1674-1-1", "1818-1-1", "IND"),
                  c("Vijayanagara Empire", "IND", "1336-1-1", "1646-1-1", "IND"),
                  c("Deccan Sultanates", "IND", "1527-1-1", "1686-1-1", "IND"),
                  c("Bahmani Sultanate", "IND", "1347-1-1", "1527-1-1", "IND"),
                  c("EIC", "IND", "1612-1-1", "1757-1-1", "ENG"),
                  c("Company Rule", "IND", "1757-1-1", "1858-1-1", "ENG"),
                  c("Maratha Empire", "IND", "1858-1-1", "1947-1-1", "ENG")
                  )

IND.factions <- data.frame(IND.factions, stringsAsFactors = FALSE)
names(IND.factions) <- c("Person", "Country", "StartDate", "EndDate", "Origin")
IND.factions$StartDate <- as.Date(IND.factions$StartDate, "%Y-%m-%d")
IND.factions$EndDate <- as.Date(IND.factions$EndDate, "%Y-%m-%d")

我想要想象的是时间轴:

library(ggplot2)
p <- ggplot(data = IND.factions, aes(y = Country)) + 
   geom_segment(aes(x = StartDate, xend = EndDate, yend = Country, color = Origin), size = 10, position = position_dodge(width = 10))
p

我找不到躲避重叠段的解决方案。有没有人有一个解决方法? 当然我知道我可以把它分成不同的因素,但这只是我的“最坏情况”解决方案

1 个答案:

答案 0 :(得分:1)

据我所知,geom_segment不允许躲避,geom_linerange会这样做。

library(ggplot2)

IND.factions <- rbind(c("Mughal Empire", "IND", "1526-1-1", "1857-1-1", "IND"),
                  c("Maratha Empire", "IND", "1674-1-1", "1818-1-1", "IND"),
                  c("Vijayanagara Empire", "IND", "1336-1-1", "1646-1-1", "IND"),
                  c("Deccan Sultanates", "IND", "1527-1-1", "1686-1-1", "IND"),
                  c("Bahmani Sultanate", "IND", "1347-1-1", "1527-1-1", "IND"),
                  c("EIC", "IND", "1612-1-1", "1757-1-1", "ENG"),
                  c("Company Rule", "IND", "1757-1-1", "1858-1-1", "ENG"),
                  c("Maratha Empire", "IND", "1858-1-1", "1947-1-1", "ENG")
                  )

IND.factions <- data.frame(IND.factions, stringsAsFactors = FALSE)
names(IND.factions) <- c("Person", "Country", "StartDate", "EndDate", "Origin")
IND.factions$StartDate <- as.Date(IND.factions$StartDate, "%Y-%m-%d")
IND.factions$EndDate <- as.Date(IND.factions$EndDate, "%Y-%m-%d")



ggplot(data = IND.factions, aes(x = Country, ymin = StartDate, ymax = EndDate, 
                                color = Origin, group = Person)) +
     geom_linerange(size = 10, position = position_dodge(.33)) +
     coord_flip()

enter image description here