由两个因素安排

问题描述 投票:0回答:1

我一整天都在尝试通过一个名为“得分”的数值来排列称为“类型”和“名称”的两个因子级别,并按分数排序按类别类型(颜色由类型确定)的图表。我也试图让名为“ALL”的组在顶部,因此它被“类型”中的其他3个类别分开。我到目前为止的尝试都非常不成功,我不明白为什么我甚至无法正确地重新排序。非常感谢任何帮助。

这是我的数据:

df = structure(list(score = c(12, 12.2, 12.5, 12.3, 12.2, 12.4, 12.5, 12.7, 12.1, 12.8, 12.4, 12.3, 12.2, 12.6, 12.8, 12.1, 12.5), range1 = c(0.003356, 1.20497, -0.128138, -42.6093, -41.1975, -44.706, -20, -46.4245, -0.543379, 2.09828, -20, -20, -44.2262, -46.6559, -20, -20, 2.37709), point = c(1.56805, 2.11176, 0.1502, -22.6093, -21.1975, -24.706, -0.491829, -26.4245, 2.49973, 2.94457, 0.0443572, 0.0208999, -24.2262, -26.6559, 2.69408, 3.22951, 3.33255), range2 = c(2.3767, 2.73239, 0.430373, 4.34247, 4.96875, 3.78027, 1.91331, 4.07937, 3.54538, 3.5491, 1.87162, 2.41067, 5.26578, 4.50965, 4.55967, 5.05772, 3.97742), type = structure(c(1L, 1L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("ALL", "A", "B", "C"), class = "factor"), name = structure(c(13L, 14L, 15L, 1L, 4L, 5L, 6L, 8L, 12L, 17L, 2L, 3L, 7L, 9L, 10L, 11L, 16L), .Label = c("B_vision1", "C_vision2", "C_vision3", "B_vision4", "B_vision5", "A_vision2", "C_vision4", "B_vision6", "C_vision6", "C_vision5", "C_vision1", "B_vision7", "B_ALL", "C_ALL", "A", "C_vision7", "B_vision3"), class = "factor")), .Names = c("score", "range1", "point", "range2", "type", "name"), row.names = c(NA, -17L), class = "data.frame")

我尝试了所有这些选项:

df$name2 = reorder(df$name, -df$score)
# df$name <- reorder(df$name, -df$score)
df <- transform(df, category2 = factor(paste(name, type)))
df <- transform(df, category2 = reorder(category2, score))

#library(plyr)
#df = arrange(df,type, name)

ggplot(df, aes(x=name, y=point, ymin=range1, ymax=range2, colour=type)) +
    geom_pointrange() +
    coord_flip()

要么

ggplot(df, aes(x=category2, y=point, ymin=range1, ymax=range2, colour=type)) +
    geom_pointrange() +
    coord_flip()

我试图得到类似于this question上的分组森林图,但每组由names定义并由score重新排序。

r ggplot2 r-factor
1个回答
0
投票

我想我已经解释了你正在尝试做的事情,但我可能错了。

名称(和分数)可以按分类排序列表排序

ordered.names  <- as.character(df$name)[order(df$score)]
ordered.scores <- as.character(df$score)[order(df$score)]

然后重新排序名称级别(带有注释的分数)

df$name <- factor(df$name, levels=ordered.names, labels=paste(ordered.names, "(", ordered.scores, ")"))

ggplot绘制这些:

library(ggplot)
ggplot(df, aes(x=name, y=point, ymin=range1, ymax=range2, group=type, color=type)) + 
  geom_pointrange() + 
  theme(axis.text.x=element_text(angle=90, hjust=0))

产生

ggplot of point by name, arranged by score, colored by type

如果你想按类型拆分,你可以面对情节

ggplot(df, aes(x=name, y=point, ymin=range1, ymax=range2, group=type, color=type)) + 
  geom_pointrange() + 
  theme(axis.text.x=element_text(angle=90, hjust=0)) + 
  facet_wrap(~type, ncol=4, scale="free_x")

ggplot of point by name, arranged by score, colored by type, facet by type

© www.soinside.com 2019 - 2024. All rights reserved.