在 R 中创建箱线图

Creating Boxplot in R

我有一个table,里面有一些产品的销量数据。我想为每个产品构建几个箱线图。 IE。纵向我有销量,横向我有天数。构建时,我不会构建某些值的箱线图。这是什么原因? 这里是 table:

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)

结果如下:

试试下面的方法:

# 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)

除了提供的答案,如果你希望纵向有销量,横向有天数(使用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 提供了三种产品的单独图表。

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