在分组条形图中设置变量的顺序

汉娜 H。

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

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

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

这也是为什么这里的方法对我不起作用的原因。此外,当我尝试在 aes 中设置顺序type = variable然后添加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)# 

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

YBS

你只需要unique在你的levels

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

你会得到

输出

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章