【问题标题】:Reversed order after coord_flip in RR中的coord_flip之后的反转顺序
【发布时间】:2016-03-17 15:04:00
【问题描述】:

来自 dbv 的数据示例:

  gender Sektion
1      m       5
2      m       5
3      w      3B
4      w      3B
5      w      3B
6      m       4

我有以下情节:

Sekplot <- ggplot(dbv,aes(x=Sektion,
                          fill=factor(gender),
                          stat="bin", 
                          label = paste(round((..count..)/sum(..count..)*100), "%"))) 
Sekplot <- Sekplot + geom_bar(position="fill")
Sekplot <- Sekplot + scale_y_continuous(labels = percent)
Sekplot <- Sekplot + labs(title = "test")
Sekplot <- Sekplot + scale_fill_discrete(name="test", breaks=c("m", "w", "k.A."), labels=c("m", "w", "k.A."))
Sekplot <- Sekplot + geom_hline(aes(yintercept = ges, linetype = "test"), colour = "black", size = 0.75, show_guide = T)
Sekplot <- last_plot() + coord_flip()
Sekplot <- Sekplot + guides(colour = guide_legend(override.aes = list(linetype = 0 )), 
                                    fill = guide_legend(override.aes = list(linetype = 0 )), 
                                    shape = guide_legend(override.aes = list(linetype = 0 )), 
                                    linetype = guide_legend()) + theme(legend.title=element_blank())

Sekplot 

输出:以错误的顺序绘制 y 轴

如何颠倒“Sektion”轴的顺序?我想在顶部有一个,在底部有 8 个。

我试过了,根据groupA$Date &lt;- factor(groupA$Date, levels=rev(unique(groupA$Date)))

Sekplot <- last_plot() + coord_flip() + scale_x_reverse()

有几种口味,但找不到正确的方法。

【问题讨论】:

  • 你需要像scale_x_discrete(limits = rev(levels(dat$Sektion)))这样的东西——见this answer
  • 非常感谢,它就像一个魅力!我无法将此问题标记为已解决,因为答案在评论中。
  • 我没有把它作为答案,因为我试图找到重复项。不过,我还没有找到一个真正好的匹配,所以将添加为答案。

标签: r ggplot2 axes


【解决方案1】:

您可以添加 scale_x_discretelimits 参数来执行此操作。你可以简单地按照你想要的顺序写出限制,但是当你有很多因子水平时,这会变得复杂。相反,您可以从数据集中提取因子的水平,并利用rev 将它们以相反的顺序排列。

它看起来像: scale_x_discrete(limits = rev(levels(dbv$Sektion)))

【讨论】:

  • forcats::fct_rev() 在这里很有用。
  • @jzadra 这对我来说仍然适用于 ggplot2 3.2.1。
【解决方案2】:

正如@sindri_baldur 所建议的,当您指定美学时,添加 fct_rev() 像这样ggplot(dbv,aes(x=fct_rev(Sektion), fill=factor(gender),stat="bin", label = paste(round((..count..)/sum(..count..)*100), "%")))

这应该就是您所需要的...从您的代码中删除scale_x_discrete()

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 2023-03-08
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多