r - ggplot2:在自由尺度上反转每个方面的离散字符变量的顺序?

标签 r ggplot2

我想绘制多面 ggplot2 点图。 x 轴是连续的,y 轴是动物列表。根据饮食行为绘制和分面两个变量。

y 轴为自由刻度,因为每只动物仅出现在一种饮食行为类别中。

library(ggplot2)

# First clean up the data set:
msleep.noNA <- msleep[!is.na(msleep$vore),]
msleep.noNA.red <-  msleep.noNA[c(1,3,6,7)]
msleep.noNA.red <- msleep.noNA.red[!is.na(msleep.noNA.red[4]),]
msleep.noNA.red <- melt(msleep.noNA.red)

pg <- ggplot(msleep.noNA.red, aes(value, name, colour = variable)) +
      geom_point() +
      facet_grid(vore ~ ., scale="free_y", space = "free_y")
pg

# Try to reverse order of the y axis:
pg + scale_y_reverse()

# Not possible because its a factor, but it's not classified as such:
class(msleep.noNA.red$name)

有人知道如何在每个子图中按字母顺序排列动物名称列表吗?

最佳答案

您可以将字符串向量转换为因子并指定级别的顺序:

以下命令将创建一个因子。级别按字母顺序降序排列:

msleep.noNA.red <- within(msleep.noNA.red,
                         name <- ordered(name, levels = rev(sort(unique(name)))))

现在您可以绘制数据:

pg <- ggplot(msleep.noNA.red, aes(value, name, colour = variable)) +
  geom_point() +
  facet_grid(vore ~ ., scale="free_y", space = "free_y")

enter image description here

关于r - ggplot2:在自由尺度上反转每个方面的离散字符变量的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14630100/

相关文章:

sql - 如何在 RPostgreSQL 中使用参数(插入数据)

r - 如何使用 lmer 在 df 中运行多个变量(列)的模型

r - 使用 facet_wrap 时 ggplot 重新排序更改

python - 在 Google Colab 上的 R 笔记本中安装 python 库

mysql - 用R还是mysql计算时间段 yield ?

r - 将 Logo 添加到 flexdashboard

r - 将参数传递给 react 函数

r - ggplot 图例斜杠

R + ggplot : coordinate transforms and geom_fill

r - 将调色板与 ggplot2 主题相关联