为什么因子的顺序不会改变

时间:2017-12-01 16:13:41

标签: r

当我绘制一个数字时,我正试图从小到大的顺序。

这是数据

df <- structure(list(label = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 
4L, 5L, 5L, 6L, 6L), .Label = c(" data1", " data10", " data15", 
" data20", " data5", " data8"), class = "factor"), variable = structure(c(1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("boys", 
"girls"), class = "factor"), N = structure(c(1L, 1L, 2L, 2L, 
3L, 3L, 4L, 4L, 5L, 5L, 6L, 6L), .Label = c("1", "10", "15", 
"20", "5", "8"), class = "factor"), value = c(93987048.3466667, 
54815262.22, 2050259639.66667, 2154175512.5, 3101847435.66667, 
2881192196, 6625604632, 3739286226.5, 270853386.15, 430516498, 
675222758.633333, 717219589.4), sd = c(129474855.769856, 48756976.8630242, 
777498079.458271, 301433971.74375, 1109031077.05936, 45164769.8052193, 
1060915464.90521, 1147931493.65351, 239740705.411582, 38453433.9415797, 
123930253.814345, 112112765.581137), se = c(74752342.8320143, 
34476388.97, 448888725.46965, 213146005.5, 640299390.87988, 31936315, 
612519829.250459, 811710143.5, 138414360.805088, 27190683.9, 
71551165.4004505, 79275696.8), ci = c(321633371.941334, 438064056.816815, 
1931412299.99575, 2708276784.58082, 2754985922.02623, 405789356.908967, 
2635460115.35016, 10313755269.7407, 595548927.354538, 345490396.550009, 
307859817.127003, 1007293234.14371)), .Names = c("label", "variable", 
"N", "value", "sd", "se", "ci"), row.names = c(NA, -12L), class = "data.frame")

基于这个答案,我应该能够将标签转换为字符,然后将因子转换为因子然后对其进行排序。 How do you specifically order ggplot2 x axis instead of alphabetical order?

所以我确实喜欢这个

df$N <- as.character(df$N)
#Then turn it back into an ordered factor
df$N <- factor(df$N, levels=unique(df$N))

如果我str df,我可以看到它将角色更改为因子,但等级不会改变

我甚至尝试手动更改等级

df$N <- factor(df$N, levels=c("1","5","8","10","15","20"))

但我仍然无法更改剧情中的顺序

所以,如果我df[order(df$N),]没有任何反应

library(ggplot2)
pd <- position_dodge(0.1) 
ggplot(df, aes(x=N, y=value, colour=variable)) + 
    geom_errorbar(aes(ymin=value-se, ymax=value+se), width=.1, position=pd) +
    geom_line(position=pd) +
    geom_point(position=pd)

2 个答案:

答案 0 :(得分:1)

N转换为字符然后转换为数字并对其进行排序。

# Sort N (Using OPs data)   
df$N2 <- factor(df$N, levels = sort(unique(as.numeric(as.character(df$N)))))

library(ggplot2)
ggplot(df, aes(N2, value, colour = variable)) + 
    geom_errorbar(aes(ymin = value - se, ymax = value + se), 
                  width = 0.1, position = pd) +
    geom_line(position = pd) +
    geom_point(position = pd)

enter image description here

答案 1 :(得分:0)

因此,您提出的问题与您所关联的问题之间似乎有所区别。在链接的问题中,他们使用X,Y和Z作为组的表示。他们希望以特定方式订购这些团体。

在这里,您正在使用数字,并且您希望它们按升序排列。您不应将它们归类为factor。相反,它们应归类为numeric

您仍然可以将numeric数据作为一个因素加载,但您需要先将其转换为character,然后再转换为numeric

df$N <- as.numeric(as.character(df$N))

pd <- position_dodge(0.1) 
ggplot(df, aes(x=N, y=value, colour=variable)) + 
  geom_errorbar(aes(ymin=value-se, ymax=value+se), width=.1, position=pd) +
  geom_line(position=pd) +
  geom_point(position=pd)

enter image description here