【问题标题】:Set order of variables in grouped barplot在分组条形图中设置变量的顺序
【发布时间】:2020-07-27 15:09:21
【问题描述】:

我的目标是有一个分组条形图,每个簇号都作为不同的条形图。这对我有用。但是,我不希望 R 重新排序我的变量。我包括了对我有用的方法。但它不再(我不知道为什么)。我现在也收到错误消息:

Error in levels<-(*tmp*, value = as.character(levels)) :   factor level [5] is duplicated

我找到了一种方法 here 来重新排序数据。但是,您需要手动包含每个变量。我想使用自动化方法,因为我必须使用不同的变量进行绘图。

这也是为什么here 方法对我不起作用的原因。此外,当我尝试使用 type = variable 设置 aes 中的排序然后添加 geom_col(aes(fill = variable)) 时,顺序不会改变,并且条形的颜色设置为灰色。

这是我的可重现示例:

library(ggplot2)

##Create dataset
first <- c("female", "male", "married", "divorced", "female", "male", "married", "divorced")
second <- c(1, 1, 1, 1, 2, 2, 2, 2)
third <- c(54, 46, 30, 70, 70, 30, 20, 80)

df <- data.frame(first, second, third)
names(df) <- c("variable", "cluster", "quantity")

##Attempt to sort the variables -> does not seem to do anything
df$variable <- factor(df$variable, levels = df$variable)

##Set colors for barplot
colors.barplot <- c("#708090", "#D53E4F", "#FBB869", "#F0E442")

##barplot of the results
ggplot(df, aes(y = quantity, x = cluster, fill = variable)) +
  geom_bar( stat = "identity", colour = "white") +
  scale_fill_manual(values = colors.barplot)# 

当我像上面那样做时,条形按字母顺序堆叠。

【问题讨论】:

    标签: r ggplot2 bar-chart stacked


    【解决方案1】:

    您只需要在您的levels 中添加unique

    df$variable <- factor(df$variable, levels = unique(df$variable))
    df$cluster <- factor(df$cluster, levels = unique(df$cluster))
    

    你会得到

    【讨论】:

    • 谢谢。这几乎对我有用。我不得不将代码更改如下: df$variable
    • 你能把它改成你的评论吗?然后我可以接受它作为答案。
    【解决方案2】:

    替换你的代码

    df$variable <- factor(df$variable, levels = df$variable)
    

    library(forcats)
    df$variable <- fct_inorder(df$variable, ordered = NA)
    

    fct_inorder 按因子在数据中出现的顺序对因子进行排序。

    【讨论】:

    • 谢谢你的作品。但是,我更喜欢没有额外包的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 2016-09-12
    • 1970-01-01
    相关资源
    最近更新 更多