# How to reverse the rows of a ggplot table.

I have written a function to plot an "at-risk" table for use with a K-M curve. The table presents the data correctly, but lists the rows of the table in the bottom to top order of the listing of the strata of the survfit object (See reprex and the resulting plot.)
Rplot01.pdf (1.7 KB)
). I need to get the program to list the first level of K-M model (strata in the reprex) as the top row of the "at-risk" table, but it lists the rows in reverse order (with the first level at-risk data on the bottom of the table. See the reprex below:

``````at.risk <- data.frame(time1 = rep(2*0:4,2),
atrisk = c(48,38,29,15,2,24,16,7,5,0),
strata = rep(c('IA', 'IAK'), each = 5))
at.risk
# time1 atrisk strata
# 1      0     48     IA
# 2      2     38     IA
# 3      4     29     IA
# 4      6     15     IA
# 5      8      2     IA
# 6      0     24    IAK
# 7      2     16    IAK
# 8      4      7    IAK
# 9      6      5    IAK
# 10     8      0    IAK

data.table <- ggplot(at.risk, aes(x = time1, y = strata)) +
geom_text(label = format(at.risk\$atrisk, nsmall = 0),
size = 10/.pt)
data.table
``````

Rplot01.pdf (1.7 KB)

I need the at.risk table to be in top down order rather than bottom up. There must be a way to do this, but I haven't discovered it. Any suggestion as to how to get the at-risk rows in top down rather than bottom up order would be gratefully received. Thanks in advance.
Larry Hunsicker

One approach could be to reverse the order of `strata`. By default character variables will be shown alphabetically (but going up, since ggplot2 charts by default have y increasing from the bottom up). To make it sort in reverse order, one of the easiest ways is to plug it into `forcats::fct_rev()`.

``````data.table <- ggplot(at.risk, aes(x = time1, y = forcats::fct_rev(strata))) +
geom_text(aes(label = format(atrisk, nsmall = 0)),
size = 10/.pt)
``````

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.