我有一张表格,里面有一些产品的销量数据。我想为每个产品构建几个箱线图。 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)
答案 0 :(得分: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)
答案 1 :(得分:1)
除了提供的答案之外,如果您希望纵向有销量,横向有天数(使用 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
提供了三种产品的单独图表。
我在这里创建了一个条形图,因为在这种情况下箱线图将毫无用处(每个产品每天只有一个值)