【问题标题】:R Combining several graphs (subcategory) in one with same scale using ggplot2 / facettingR使用ggplot2 / facetting将多个图形(子类别)组合成一个具有相同比例的图形
【发布时间】:2013-09-20 11:27:16
【问题描述】:

我有几个类别(A,B,C)和子类别(A01,B01,B02,...)的数据。我想在一个独特的图表中包含按类别划分的子类别(共享相同的比例)。

这是我的工作流程示例:

library(ggplot2)
library(plyr)

# Create data
subcategory <- c("A01", "A02", "A03", "B01", "B02", "C01", "C02", "D01")
qty <- c(4, 5, 3, 8, 4, 2, 1, 6)
df <- data.frame(subcategory=subcategory, qty=qty)
df$category <- factor(str_extract(df$subcategory, "[A-Z]"))

# Data aggregation
df.ply <- ddply(df, .(subcategory, category), summarize, qty=sum(qty))

# Plotting
plot <- ggplot(df.ply, aes(x=subcategory, y=qty, fill=category))
plot + geom_bar(stat="identity") + facet_grid(category~.) 

所以这个汇总表:

    subcategory category    qty
1   A01         A           4
2   A02         A           5
3   A03         A           3
4   B01         B           8
5   B02         B           4
6   C01         C           2
7   C02         C           1
8   D01         D           6

给我这张照片:

...我希望每个方面都只有相应的子类别(删除空的子类别)。 ggplot2 可以吗?

我应该使用视口和子图而不是刻面吗?我对如何在我的用户案例中为 ggplot2 改编 Hadley Wickam 书中的说明 p146 感到非常迷茫......

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    只需更改代码的最后一行:

    plot + geom_bar(stat="identity") + facet_wrap(~category, scales="free") 
    

    你仍然可以使用facet_grid:

    plot + geom_bar(stat="identity") + facet_grid(~category, scales="free") 
    

    facet_wrap 让您也可以选择方面的 nrow 和 ncol。

    【讨论】:

      猜你喜欢
      • 2017-07-20
      • 2016-03-27
      • 1970-01-01
      • 2019-04-09
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多