【问题标题】:Manually set order of fill bars in arbitrary order using ggplot2 [duplicate]使用ggplot2以任意顺序手动设置填充条的顺序[重复]
【发布时间】:2014-07-19 12:46:39
【问题描述】:

我正试图弄清楚如何转换我的条形图。现在,Gears 填充是按数字顺序排列的。我正在尝试能够手动设置Gears的顺序填写任意顺序。

我发现的所有其他示例都告诉我如何根据数据的计数或值以降序或升序对它们进行排序。我正在尝试以任意顺序手动设置顺序。因此,我想手动告诉它我希望数据显示为 3-5-4 或 5-3-4,而不是 3-4-5。

这是我现在拥有的:

library(data.table)
library(scales)
library(ggplot2)

mtcars <- data.table(mtcars)
mtcars$Cylinders <- as.factor(mtcars$cyl)
mtcars$Gears <- as.factor(mtcars$gear)
setkey(mtcars, Cylinders, Gears)
mtcars <- mtcars[CJ(unique(Cylinders), unique(Gears)), .N, allow.cartesian = TRUE]

ggplot(mtcars, aes(x=Cylinders, y = N, fill = Gears)) + 
               geom_bar(position="dodge", stat="identity") + 
               ylab("Count") + theme(legend.position="top") + 
               scale_x_discrete(drop = FALSE)

如果有任何不涉及ggplot2 的数据操作,我想使用data.table 来完成。感谢您的帮助!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您需要正确设置因子水平。

    假设你有一个因素

    > x=factor(c("a","c","b"))
    > x
    [1] a c b
    Levels: a b c
    

    顺序为a c b,但绘图顺序为a b c,因为默认因子以字母数字顺序生成水平。

    也许您希望绘图顺序与向量中的顺序相匹配——我们可以指定因子水平应该遵循每个水平第一次遇到的顺序:

    > z=factor(x,unique(x))
    > z
    [1] a c b
    Levels: a c b
    

    也许我们都不想要这些——例如我们可能想要c a b

    我们可以手动设置顺序

    > y=factor(c("a","c","b"),levels=c("c","a","b"))
    > y
    [1] a c b
    Levels: c a b
    

    或者我们可以稍后通过明确指定每个级别的位置来调整一个因素:

    > reorder(y,x,function(x)c(a=2,b=3,c=1)[x])
    [1] a c b
    attr(,"scores")
    c a b 
    1 2 3 
    Levels: c a b
    

    现在你知道了,你可以应用你在别处找到的技术,比如

    Order Bars in ggplot2 bar graph

    【讨论】:

      猜你喜欢
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2022-08-24
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多