【问题标题】:ggplot2 column chart with facet_grid带有 facet_grid 的 ggplot2 柱形图
【发布时间】:2025-12-17 13:05:01
【问题描述】:

我正在尝试制作一个 R ggplot2 图表,其中的列将一个变量分组,而 facet_grid 则由另一个变量分解。我尝试过的两种方法都失败了:

1) 将x 设置为facet_grid 变量会被该变量分解两次:

ggplot(diamonds, aes(x=cut, y=price, fill=color)) +
    geom_bar(position="dodge", stat="identity") +
    facet_grid(cut ~ ., scales="free")

2) 删除 x 会产生错误:

ggplot(diamonds, aes(y=price, fill=color)) +
    geom_bar(position="dodge", stat="identity") +
    facet_grid(cut ~ ., scales="free")
# Error in exists(name, envir = env, mode = mode): 
# argument "env" is missing, with no default

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    x 设置为与color arg 相同的变量:

    ggplot(diamonds, aes(x=color, y=price, fill=color)) +
        geom_bar(position="dodge", stat="identity") +
        facet_grid(cut ~ ., scales="free")
    

    【讨论】:

    • 这些价格值似乎不准确。例如,Fair 和颜色 D 的钻石的平均价格是 4291 美元,并且该图显示了 3 倍高的价值。钻石 %>% 过滤器(cut == "Fair", color == "D")%>% summarise(price = mean(price, na.rm = TRUE))