【问题标题】:Plotting order within a faceted dotchart in ggplot2在ggplot2中的多面点图中绘制顺序
【发布时间】:2011-01-23 16:12:41
【问题描述】:

我正在尝试在 ggplot2 中创建一个多面点图,但无法获得内面 类别以我想要的顺序出现。绘制点图的代码是:

g <- ggplot(df2, aes(x=Y, y=label)) + geom_point() 
g <- g + facet_grid(incentive ~ .,   scale="free")
g <- g + geom_errorbarh(aes(xmax = Y + se, xmin = Y - se))  
g <- g + geom_vline(xintercept=1/6, linetype=2, colour="red") 
g <- g + opts(title="% Subjects Choosing Non-Focal Image",
          strip.text.y = theme_text()
          ) + xlab("%") + ylab("Groups")
print(g)

该图的问题在于,在“仅限金钱”方面,1 美分和 5 美分类别的顺序错误。问题似乎不是因素本身的顺序,因为:

> levels(df2$label)
[1] "0"      "1"      "1 cent" "5 cent" "6"     
> 

更新:对因子排序似乎不会改变绘图顺序,即使用 label3 绘图,其中:

df2$label3 1 0 1 1 美分 5 美分 6
级别:0

>str(df2$label3)
Ord.factor w/ 5 levels "0"<"1"<"1 cent"<..: 1 2 3 4 5

实际数据框:

df2 <- structure(list(Y = c(0.0869565217391304, 0.148148148148148, 0.172413793103448, 
0.384615384615385, 0.5625), group = c(0L, 1L, 5L, 3L, 6L), se = c(0.0856368459098186, 
0.079039229753282, 0.0762650540661762, 0.0805448741815074, 0.0726021684593052
), nudged = c(FALSE, TRUE, TRUE, TRUE, TRUE), incentive = structure(c(1L, 
2L, 3L, 3L, 4L), .Label = c("Default behavior", "Imbalance only", 
"Money only", "Money & Imbalance together"), class = "factor"), 
label = structure(1:5, .Label = c("0", "1", "1 cent", "5 cent", 
"6"), class = "factor"), plot_order = c(0, 1, 2, 3, 4)), .Names = c("Y", 
"group", "se", "nudged", "incentive", "label", "plot_order"), 
row.names = c("as.factor(group)0", 
"as.factor(group)1", "as.factor(group)5", "as.factor(group)3", 
"as.factor(group)6"), class = "data.frame")

【问题讨论】:

  • 他们不是已经安排好了吗?请记住,y 轴在底部具有最小值。

标签: r ggplot2


【解决方案1】:

您的问题是facet_grid 正在绘制 incentive-types(“默认行为”等)的顺序与 incentive-value(0、1 美分、5 美分等),这就是为什么您没有在 Money Only 组中获得所需的排序。修复它的最简单方法是重新排序 incentive 因子,以便将默认行为绘制在 bottom 而不是 top:

df2$incentive <- ordered( df2$incentive,
                 levels = rev(c("Default behavior", "Imbalance only", 
                                "Money only", "Money & Imbalance together"))) 

并保持其余代码不变。然后你得到这个情节:

【讨论】:

  • 为了概括这个解决方案,如果列(比如df2$incentive)按照您希望的顺序(从上到下),那么df2$incentive &lt;- ordered(df2$incentive, levels = rev(unique(df2$incentive))) 将节省您输入因子水平顺序正确。 (当我发现这个问题时,我有 38 个因素,每个因素都有一个学名。)
【解决方案2】:

这听起来和看起来都非常奇怪(因为标签是按因子级别的顺序排序的,正如@Dirk Eddelbuettel 在上面也写的那样),但您始终可以使用scale_discrete。

我根据你的代码做了一个小例子,但是看起来也有点奇怪,看:

g <- ggplot(df2, aes(x=Y, y=label)) + geom_point()
# add manual scale
g <- g+ scale_y_discrete(limits=c("0","1","1 cent","5 cent","6"))
g <- g + facet_grid(incentive ~ .,   scale="free")
g <- g + geom_errorbarh(aes(xmax = Y + se, xmin = Y - se))  
g <- g + geom_vline(xintercept=1/6, linetype=2, colour="red") 
g <- g + opts(title="% Subjects Choosing Non-Focal Image",
      strip.text.y = theme_text()
      ) + xlab("%") + ylab("Groups")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-10
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多