【问题标题】:Creating Boxplot in R在 R 中创建箱线图
【发布时间】:2021-08-22 07:33:09
【问题描述】:

我有一张表格,其中包含一些产品的销量数据。我想为每个产品建立几个箱线图。 IE。纵向我有销量,横向我有天数。构建时,我不会以某些值构建箱线图。这是什么原因? 这是表格:

Day Cottage cheese..pcs. Kefir..pcs. Sour cream..pcs.
1    1          99        103          111
2    2          86        101          114
3    3          92        100          116
4    4          87        112          120
5    5          86        104          111
6    6          88        105          122
7    7          88        106          118

这是我的代码:

head(out1)# out1-the table above
boxplot(Day~Cottage cheese..pcs., data = out1)

结果如下:

【问题讨论】:

  • 请粘贴可重现的例子:dput(out1)
  • 您在白干酪列中有 5 个唯一值,所以您有 5 个箱线图?预期的输出是什么?
  • @zx8754 我想为每个产品做一个箱线图,我不知道如何为每个产品做,开始单独做

标签: r plot boxplot


【解决方案1】:

试试下面:

# example data
out1 <- read.table(text = " Day Cottage.cheese Kefir Sour.cream
1    1          99        103          111
2    2          86        101          114
3    3          92        100          116
4    4          87        112          120
5    5          86        104          111
6    6          88        105          122
7    7          88        106          118", header = TRUE)

# reshape wide-to-long
outlong <- stats::reshape(out1, idvar = "Day", v.names = "value",
                          time = "product", times = colnames(out1)[2:4],
                          varying = colnames(out1)[2:4], direction = "long")

# then plot
boxplot(value~product, outlong)

【讨论】:

  • 您能解释一下这个stats::reshape 结构是什么以及它的用途吗?
  • @sjr_25 它被称为reshaping from wide-to-long format。还有很多其他方法可以做到这一点,请参阅链接的帖子。
  • @zx8754 为什么我们需要重塑?我无法理解
  • @sjr_25 我的情节是否符合您的预期输出?我们需要重塑,因为我们需要绘制 2 个值:x 轴上的产品类型和 y 轴上的销量(价值)。
  • @zx8754 是的,一切都匹配!谢谢你的解释
【解决方案2】:

除了提供的答案之外,如果您希望纵向有销量,横向有天数(使用 zx8754 提供的out1 数据)。

library(tidyr)
library(data.table)
library(ggplot2)

#data from wide to long
dt <- pivot_longer(out1, cols = c("Kefir", "Sour.cream", "Cottage.cheese"), names_to = "Product", values_to = "Value")

#set dt to data.table object
setDT(dt)

#convert day from integer to a factor
dt[, Day := as.factor(Day)]

#ggplot
ggplot(dt, aes(x = Day, y = Value)) + geom_bar(stat = "identity") + facet_wrap(~Product)

facet_wrap 为三种产品提供单独的图表。

我在这里创建了一个条形图,因为在这种情况下箱线图将毫无用处(每个产品每天只有一个值)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多