首页 > 解决方案 > 在ggplot中对Y轴上不完整的数值字符串进行排序

问题描述

我正在尝试在我的 ggplot 中使用 y 轴上的参与者记录 ID。记录 ID 会跳来跳去(例如 1、3、10、100)。我的问题是三个方面:

  1. 我想在 y 轴上显示每个 ID,但是当我转换为 时as.numeric(as.character(record_id))),轴是有序的,但没有考虑到记录 ID 跳过。

  2. 如果我转换为 as.character,这是正确的概念,但我不知道如何排序,因此即使使用str_order.

    到目前为止,使用ggplot(sincevax_reshape, aes(x=value, y=as.character(sort(as.numeric(record_id)))))已经让我看到了 y 轴的外观,但不是正确的排序。

  3. 一旦我让记录 ID 在 Y 轴上正确排序,有没有办法增加每个记录 ID 之间的垂直间距,这样 Y 轴就不会那么拥挤/聚集?

     record_id  variable value
6           10    Sample  -182
7           11    Sample  -233
14          21    Sample  -189
16          23    Sample  -232
17          24    Sample  -214
21          30    Sample  -197
23          32    Sample  -133
24          33    Sample  -203
28          39    Sample  -165
29          41    Sample  -226
1105         3     Today   106
1106         4     Today   163
1107         6     Today    79
1108         7     Today   113
1109         9     Today   133
1110        10     Today   177
1111        11     Today   118

最终目标是这样的,顶部没有所有空格:

标签: rsortingggplot2

解决方案


您可以尝试将数字转换为因子:

library(ggplot2)

df$record_id <- factor(df$record_id, levels = df$record_id)

ggplot(df, aes(x = value, y = record_id)) + 
  geom_col()

reprex 包于 2021-08-17 创建 (v2.0.0 )

使用的数据

df <- structure(list(record_id = c(10L, 11L, 21L, 23L, 24L, 30L, 32L, 
33L, 39L, 41L), variable = c("Sample", "Sample", "Sample", "Sample", 
"Sample", "Sample", "Sample", "Sample", "Sample", "Sample"), 
    value = c(-182L, -233L, -189L, -232L, -214L, -197L, -133L, 
    -203L, -165L, -226L)), class = "data.frame", row.names = c("6", 
"7", "14", "16", "17", "21", "23", "24", "28", "29"))

推荐阅读