【问题标题】:dogded barcharts with ggplot2 and two variables on x axis带有 ggplot2 和 x 轴上的两个变量的闪避条形图
【发布时间】:2026-02-04 15:40:02
【问题描述】:

根据这些数据

library(ggplot2)
library(reshape2)    
test <- structure(list(Name = structure(c(3L, 1L, 2L), .Label = c("Bob", 
    "Marc", "Tim"), class = "factor"), Group = structure(1:3, .Label = c("A", 
    "B", "C"), class = "factor"), X2012 = 11:13, X2013 = c(14L, 15L, 
    15L), X2014 = c(12L, 14L, 13L)), .Names = c("Name", "Group", 
    "X2012", "X2013", "X2014"), class = "data.frame", row.names = c(NA, 
    -3L))
test.melt <- melt(test)
names(test.melt) <- c("Name", "Group", "Year", "Mean")

我想创建一个条形图,将“名称”列中的三个因子水平作为主要的 x 轴变量。三个级别(Bob、Marc、Tim)中的每一个都应该有三个闪避的条(“Year”级别),并且应该用“Group”着色。绘制在 y 轴上的应该是“平均值”中给出的值。 我试过了

ggplot(test.melt, aes(x=Name, y=value, fill=Group)) +
  geom_bar(stat="identity", position="dodge")

但我不知道如何告诉 ggplot2 要躲避什么,即如何处理“年”。有解决办法吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您必须在某处将年份用作组类别。在这里,我使用了颜色,但它也适用于形状,但对于后者,您看不到哪个条对应于哪一年。

    ggplot(test.melt, aes(x=Name, y=Mean, fill=Group, color=Year)) +
    geom_bar(stat="identity", position="dodge")
    

    【讨论】: