【问题标题】:如何在 ggplot2 for R 中设置填充变量的顺序
【发布时间】:2022-01-23 07:15:57
【问题描述】:

我想知道是否有一种方法可以为 ggplot 中的并排条形图定义每组的出现顺序。我的数据集是

> 东风 V1 V2 V3 1 真关节 0.18 2 真实个人 0.82 3 估计联合 0.37 4 估计个人 0.63

以下代码行

library(ggplot2)

ggplot(df, aes(x = V2, y = V3, fill = V1)) +
  geom_col(position = position_dodge2()) +
  scale_fill_manual(values=c("steelblue","coral2")) +
  guides(fill = guide_legend(reverse = T)) +
  scale_x_discrete(limits = unique(df$V2)) +
  theme(legend.title = element_blank()) +
  xlab("Structure") + ylab("Variance") +
  ggtitle("Variance Explained by Joint and Individual structure")

给我这张图 side-by-side-barplot.

对于每个组,我希望珊瑚色条位于左侧,蓝色条位于右侧。我尝试使用代码行重新排序数据集,例如

df = arrange(df, df$V1)
df = df[order(df$V1, decreasing = F),]
df = df[c(1,3,2,4),]
df = df[c(1,4,3,2),]

但他们没有工作。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以通过转换为factor 并按您想要的顺序设置级别来达到您想要的结果:

    此外,我使用了一个命名向量来将颜色分配给类别。但这只是个人喜好问题。

    library(ggplot2)
    
    ggplot(df, aes(x = V2, y = V3, fill = factor(V1, levels = c("True", "Estimate")))) +
      geom_col(position = position_dodge2()) +
      scale_fill_manual(values = c(Estimate = "steelblue", True = "coral2")) +
      guides(fill = guide_legend(reverse = T)) +
      scale_x_discrete(limits = unique(df$V2)) +
      theme(legend.title = element_blank()) +
      xlab("Structure") +
      ylab("Variance") +
      ggtitle("Variance Explained by Joint and Individual structure")
    

    数据

    df <- structure(list(
      V1 = c("True", "True", "Estimate", "Estimate"),
      V2 = c("Joint", "Individual", "Joint", "Individual"), V3 = c(
        0.18,
        0.82, 0.37, 0.63
      )
    ), class = "data.frame", row.names = c(
      "1",
      "2", "3", "4"
    ))
    

    【讨论】:

    • 我不明白为什么,但你的方法行得通。如果我在我的程序中为绘图生成相同的代码行,它就不起作用。您创建数据集的方式有所不同。我使用了以下代码行df = as.data.frame(cbind(c(rep("True", 2), rep("Estimate", 2)), rep(c("Joint", "Individual"), 2), c(0.18,0.82,0.37,0.63)), row.names = 1:4)
    • (: 其实我想知道为什么你得到不同顺序的条。关于数据框,没有什么特别的。我添加数据的方式是通过dput()函数(试试看您的数据:dput(df)),这是在 SO 上共享数据的首选方式。可以轻松地以保留数据类型的可复制格式复制数据。通过您用于创建的代码添加数据也可以更多信息请参阅how to make a minimal reproducible example
    【解决方案2】:

    您可以简单地将reverse = TRUE 参数添加到position_dodge2

    ggplot(df, aes(x = V2, y = V3, fill = V1)) +
      geom_col(position = position_dodge2(reverse = TRUE)) +
      scale_fill_manual(values=c("steelblue","coral2")) +
      guides(fill = guide_legend(reverse = T)) +
      scale_x_discrete(limits = unique(df$V2)) +
      theme(legend.title = element_blank()) +
      xlab("Structure") + ylab("Variance") +
      ggtitle("Variance Explained by Joint and Individual structure")
    

    【讨论】:

    • 你的方法也行。我认为问题在于我将数据集导入 R 的方式。不知道为什么......
    猜你喜欢
    • 2014-07-19
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    相关资源
    最近更新 更多