ggplot2中离散y轴的逆序

时间:2015-02-08 07:59:26

标签: r ggplot2

情况&数据

我在比赛中有一个df运动员位置的数据框(我已经melted用于ggplot2):

df <- structure(list(athlete = c("A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", 
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "A", "B", "C", 
"D", "E", "F", "G", "H", "I", "J", "A", "B", "C", "D", "E", "F", 
"G", "H", "I", "J", "A", "B", "C", "D", "E", "F", "G", "H", "I", 
"J"), distanceRemaining = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 
4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 
6L, 6L, 6L, 6L, 6L, 6L), .Label = c("1400m", "1200m", "600m", 
"400m", "200m", "FINISH"), class = "factor"), position = c(10, 
6, 7, 8, 2, 1, 3, 5, 9, 4, 9, 8, 7, 6, 4, 3, 1, 5, 10, 2, 8, 
7, 9, 5, 6, 2, 3, 1, 10, 4, 9, 8, 6, 5, 7, 3, 2, 4, 10, 1, 4, 
5, 1, 6, 8, 3, 2, 7, 10, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)), row.names = c(NA, 
-60L), .Names = c("athlete", "distanceRemaining", "position"), class = "data.frame")

我用

绘制数据
library(ggplot2)
g <- ggplot(df, aes(x=distanceRemaining, y =position, colour=athlete, group = athlete))
g <- g + geom_point()
g <- g + geom_line(size=1.15)
g <- g + scale_y_discrete()
g

给予

athletePositions

问题

如何反转y轴的顺序,使10位于底部,1位于顶部?

6 个答案:

答案 0 :(得分:19)

您只需将位置变量转换为一个因子,然后反转其级别:

require(dplyr)
df <- df %>% mutate(position = factor(position), 
                    position = factor(position, levels = rev(levels(position)))

然后使用您的代码,您将获得: enter image description here

答案 1 :(得分:15)

尝试以下方法:

g <- ggplot(df, aes(x=distanceRemaining, y =position, colour=athlete, group = athlete))
g <- g + geom_point()
g <- g + geom_line(size=1.15)
g <- g +  scale_y_continuous(trans = "reverse", breaks = unique(df$position))
g

enter image description here

答案 2 :(得分:13)

根据https://gist.github.com/jennybc/6f3fa527b915b920fdd5

添加scale_y_discrete(limits = rev(levels(theFactor))) 你的ggplot命令。

答案 3 :(得分:8)

对于离散轴,使用reorder()为我工作。在上述问题的背景下,它看起来像这样:

ggplot(df, aes(x = distanceRemaining, y = reorder(position, desc(position))))

希望这有帮助。

答案 4 :(得分:3)

有一个new解决方案,scale_*_discrete(limits=rev),例如:

tibble(x=1:26,y=letters) %>% 
  ggplot(aes(x,y)) +
    geom_point() +
    scale_y_discrete(limits=rev)

enter image description here

答案 5 :(得分:1)

使用forcats软件包的另一个选项。

ggplot(df, aes(x = distanceRemaining, y = forcats::fct_rev(factor(position))))

这具有将所有内容保留在ggplot调用中并与coord_flipfacets_wrap(..., scales = "free")之类的其他选项很好地配合的优点。