【问题标题】:Sub setting data R plot子设定数据 R plot
【发布时间】:2016-09-23 17:31:10
【问题描述】:

我正在尝试绘制一个图表,它显示特定类的数字列中的总价值,例如 1、3、5 等。

这是我的示例数据:

test <- data.frame("number"=sample(1:10),"class"=c(1,1,2,2,3,3,4,4,5,5))

我使用下面的代码:

number <- test$number
class <- test$class
png("plot1_test.png", width=600, height=600)
plot(class, number, type="h", xlab="Class", ylab="Sum of number")
dev.off()

结果出来它只识别每个类的第一个值。如果我想要总数,是否需要按总数对每个班级进行子集?以及如何创建仅显示某些类而不是全部的图?

【问题讨论】:

    标签: r plot subset


    【解决方案1】:

    尝试使用aggregate。它将根据class中的值将函数sum应用于test$number数据。

    test.aggreg <- aggregate(test$number, by=list(test$class), sum)
    plot(test.aggreg, type="h", xlab="Class", ylab="Total for Class")
    

    它看起来像

    【讨论】:

    • 那很好,我怎么能只想显​​示类 1 ,3 和 5?
    • test.aggreg 数据框进行切片。使用test.aggreg[c(1,3,5),]。实际上,任何订单都可以。如:test.aggreg[c(5,3,1),]
    【解决方案2】:

    使用ggplot2的简单解决方案:

    library(ggplot2)
    ggplot(test, aes(class,number)) + geom_bar(stat="identity")
    

    或者,如果你不想使用 ggplot2,聚合(使用 dplyr):

    library(dplyr)
    plotdb <- test %>% group_by(class) %>%
      summarise(sum_number = sum(number))
    

    然后,使用您最喜欢的带有类和 sum_number 的绘图函数。

    关于最后一个问题:为了只选择一些类,您可以在第一个选项中添加一个 dplyr::filter:

    library(ggplot2)
    library(dplyr)
    ggplot(filter(test,class %in% 1:3), aes(class,number)) + geom_bar(stat="identity")
    

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 1970-01-01
      • 2017-12-15
      • 2022-06-10
      • 2017-05-13
      • 2014-08-13
      • 1970-01-01
      • 2014-06-12
      • 2016-01-10
      相关资源
      最近更新 更多