Search code examples
rplotlinegraph

vertical line chart - change line plotting direction to top-down in R


I am looking for a way where data points are connected following a top-down manner to visualize a ranking. In that the y-axis represents the rank and the x-axis the attributes. With the normal setting the line connects the point starting from left to right. This results that the points are connected in the wrong order.

With the data below the line should be connected from (6,1) to (4,2) and then (5,3) etc. Optimally the ranking scale need to be inverted so that rank one starts on the top.

data <- read.table(header=TRUE, text='
attribute rank
1    6
2    5
3    4
4    2
5    3
6    1
7    7
8   11
9   10
10    8
11    9
')

plot(data$attribute,data$rank,type="l")

Is there a way to change the line drawing direction? My second idea would be to rotate the graph or maybe you have better ideas.

The graph I am trying to achieve is somewhat similar to this one: example vertical line chart


Solution

  • You can do this with ggplot:

    library(ggplot2)
    ggplot(data, aes(y = attribute, x = rank)) + 
      geom_line() + 
      coord_flip() +
       scale_x_reverse()
    

    It solves the problem exactly the way you suggested. The first part of the command (ggplot(...) + geom_line()) creates an "ordinary" line plot. Note that I have already switched x- and y-coordinates. The next command (coord_flip()) flips x- and y-axis, and the last one (scale_x_reverse) changes the ordering of the x-axis (which is plotted as the y-axis) such that 1 is in the top left corner.

    Just to show you that something like the example you linked in your question can be done with ggplot2, I add the following example:

    library(tidyr)
    data$attribute2 <- sample(data$attribute)
    data$attribute3 <- sample(data$attribute)
    plot_data <- pivot_longer(data, cols = -"rank")
    
    ggplot(plot_data, aes(y = value, x = rank, colour = name)) + 
      geom_line() +
      geom_point() + 
      coord_flip() + 
      scale_x_reverse()
    

    enter image description here

    If you intend to do your plots with R, learning ggplot2 is really worthwhile. You can find many examples on Cookbook for R.