Reverse order of discrete y axis in ggplot2

前端 未结 6 672
情歌与酒
情歌与酒 2020-12-01 06:10

Situation & data

I have a dataframe df of athlete positions in a race (I\'ve already melted it for use with ggpl

相关标签:
6条回答
  • 2020-12-01 06:32

    Another option using the forcats package.

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

    This has the advantage of keeping everything in the ggplot call, and playing nicely with other options such as coord_flip and facets_wrap(..., scales = "free")

    0 讨论(0)
  • 2020-12-01 06:42

    For a discrete axis, using reorder() worked for me. In context of the above problem, it would look something like this:

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

    Hope this helps.

    0 讨论(0)
  • 2020-12-01 06:45

    Try the following:

    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

    0 讨论(0)
  • 2020-12-01 06:45

    There is a new solution, scale_*_discrete(limits=rev), example:

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

    0 讨论(0)
  • 2020-12-01 06:52

    You just need to turn the position variable into a factor and then reverse its levels:

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

    And then with your code you'd get: enter image description here

    0 讨论(0)
  • 2020-12-01 06:53

    as per https://gist.github.com/jennybc/6f3fa527b915b920fdd5:

    add scale_y_discrete(limits = rev(levels(theFactor))) to your ggplot command.

    0 讨论(0)
提交回复
热议问题