我想绘制一个刻面的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)
有没有人知道如何在每个子图中按字母顺序列出动物名称?
答案 0 :(得分:9)
您可以将字符串向量转换为因子并指定级别的顺序:
以下命令将创建一个因子。级别按字母顺序递减:
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")