【问题标题】:How to subset a longtable in R and create boxplots with ggplot如何在 R 中对 longtable 进行子集化并使用 ggplot 创建箱线图
【发布时间】:2015-05-02 21:34:36
【问题描述】:

举个例子:

set.seed(1)
tmp.data<-data.frame(group=rep(c("x","y","z"),8),
year=rep(c(2000:2003),6),
value=runif(24, 1, 100)) 

我可以创建一个带有团体隶属关系的简单箱线图:

boxplot.example<-ggplot(data=tmp.data)
boxplot.example.simple<-boxplot.example +
geom_boxplot(aes(x=group,y=value))

# plot
boxplot.example.simple

但是,我想在同一图形中为每个组和年份创建单独的箱线图。

我用 ggplot 的 group 函数试了一下:

boxplot.example.yearly<-boxplot.example +
geom_boxplot(aes(x=year,y=value, group=group))

# plot
boxplot.example.yearly # does not work as expected

但是,分组没有按预期工作。

然后我尝试像这样使用splitllply

require("plyr")

boxplot.example.yearly.2<-ggplot() +
llply(.data=split(tmp.data,tmp.data$year),.fun=geom_boxplot,
aes(x=year,y=value))

# Error: ggplot2 doesn't know how to deal with data of class uneval

这可能是由于数据参数未在 ggplot 函数中指定。

那么如何将箱线图绘制成一个按group 和年度观察分组的图表?

【问题讨论】:

    标签: r plot ggplot2 subset plyr


    【解决方案1】:

    由于您想在同一图表中为每个组和年份生成箱线图,我认为您的数据集已经准备好,您可以执行以下操作:

    p <- ggplot(tmp.data, aes(factor(year), fill=group, value)) 
    p + geom_boxplot()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多