【问题标题】:How to get ggplot2 geom_bar to plot axis by it's factor levels and not by default sorting如何让ggplot2 geom_bar按其因子水平而不是默认排序来绘制轴
【发布时间】:2019-11-17 14:44:09
【问题描述】:

我想在 ggplot2 中制作一个条形图,并让 ggplot2 按照我在 Day44$Sample 列中提供的顺序绘制我的 X 轴。这是一个例子(我的真实数据在 Day44$Sample 列中有 59 个因子水平。

Day44 <- data.frame(Sample = c(rep(6, 3), rep(8, 5), rep(12, 8), rep(100, 7), rep("41*", 3), rep("198*", 5)),
                Phylum = c(rep("Proteobacteria", 3), rep("Actinobacteria", 5), rep("Firmicutes", 8), 
                          rep("Chloroflexi", 7), rep("Cyanobacteria", 3), rep("Bacteroidetes", 5)), 
                Rel_Abund = c(rep(2.2, 3), rep(0.15, 5), rep(0.047, 8), rep(1.2, 7), rep(0.33, 3), rep(4.5, 5)))

我已经读过,为了以与我的专栏相同的顺序绘制,我必须“告诉”ggplot2 我已经有一个有序因子 - 基于这篇文章:Avoid ggplot sorting the x-axis while plotting geom_bar()

关注帖子:

Day44$Sample <- factor(Day44$Sample, levels = Day44$Sample)

当我收到以下错误时:

levels&lt;-(*tmp*, value = as.character(levels)) 中的错误: 因子级别2 重复

所以,我找到了这个帖子:Warning when defining factor: duplicated levels in factors are deprecated

并遵循这条线索(省略帖子中推荐的sort,因为我不需要对其进行排序):

Day44$Sample <- factor(Day44$Sample, levels = unique(Day44$Sample)

然后我用它来绘制:

ggplot() + geom_bar(aes(x = Sample, y = Rel_Abund, fill = Phylum), data = Day44, stat = 'identity')

然而,它给了我一个不错的条形图;无论如何,x轴都是排序的。

这段代码提示我进入错误,它给出:

factor(unique(Day44$Sample))

6 8 12 100 41* 198*

等级:100 12 198* 41* 6 8

如何将其更改为我的级别与 Day44$Sample 的唯一值的顺序相同?

我知道我可以手动将它们放入,如下所示:

Day44$Sample <- factor(Day44$Sample, levels = c("6", "8", "12", "100", "41*", "198*"))

生成我想要的确切图表,但这不切实际,因为我的真实数据有 59 个级别,而且我还必须使用多个其他图表来执行此操作。我永远不会手动完成此操作。

有什么建议吗?

【问题讨论】:

    标签: r ggplot2 geom-bar factors


    【解决方案1】:

    如果您想根据它们在数据框中出现的顺序对因子水平进行排序,请使用forcats::fct_inorder

    Day44$Sample = forcats::fct_inorder(Day44$Sample)
    

    【讨论】:

    • 再想一想,Day44$Sample &lt;- factor(Day44$Sample, levels = unique(Day44$Sample)) 应该有效 - 可能值得再次尝试以仔细检查您的理解。
    • 感谢您的推荐。我安装了包forcats 并运行了代码,它运行得非常好!谢谢。
    猜你喜欢
    • 2015-09-29
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多