我有一个数据集(测试),如下所示:
Type Met1 Met2 Met3 Met4
TypeA 65 43 97 77
TypeA 46 25 76 77
TypeA 44 23 55 46
TypeA 46 44 55 77
TypeA 33 22 55 54
TypeB 66 8 66 47
TypeB 55 76 66 65
TypeB 55 77 88 46
TypeB 36 67 55 44
TypeB 67 55 76 65
Run Code Online (Sandbox Code Playgroud)
我在盒子图上检查了很多链接,但是我仍然没有成功获得我想要的盒子图.我希望有一个箱形图,我的X轴有所有Mets(Met1,Met2,Met3,Met4)的A型(黄色,橙色).从本质上讲,我想要以下内容(取自此处):
我正在尝试一些事情,比如
boxplot(formula = len ~ Type , data = test, subset == "TypeA")
boxplot(formula = len ~ Type , data = test, subset == "TypeA", add=TRUE)
Legend(legend = c( "typeA", "typeB" ), fill = c( "yellow", "orange" ) )
Run Code Online (Sandbox Code Playgroud)
但我无法解决任何问题.任何人都可以帮助我知道如何以更正的方式在我的测试数据上制作这样的箱形图?
Sve*_*ein 20
一个解决方案ggplot2
.
首先,使用以下方法将数据帧test
转换为长格式melt
:
library(reshape2)
test.m <- melt(test)
Run Code Online (Sandbox Code Playgroud)
绘制数据:
library(ggplot2)
ggplot(test.m, aes(x = variable, y = value, fill = Type)) +
geom_boxplot() +
scale_fill_manual(values = c("yellow", "orange"))
Run Code Online (Sandbox Code Playgroud)
正如其他人所说,首先你需要融化你的数据.
df <- read.table(text="Type Met1 Met2 Met3 Met4
TypeA 65 43 97 77
TypeA 46 25 76 77
TypeA 44 23 55 46
TypeA 46 44 55 77
TypeA 33 22 55 54
TypeB 66 8 66 47
TypeB 55 76 66 65
TypeB 55 77 88 46
TypeB 36 67 55 44
TypeB 67 55 76 65",header=TRUE)
library(reshape2)
df2 <- melt(df)
boxplot(
formula = value ~ variable,
data = df2,
boxwex = 0.25,
at = 1:4 - 0.2,
subset = Type == "TypeA",
col = "yellow",
main = "blah",
xlab = "x",
ylab = "y",
ylim = c( 0, ceiling( max( df2$value ) ) + 1 ),
yaxs = "i" )
boxplot(
formula = value ~ variable,
data = df2,
boxwex = 0.25,
at = 1:4 + 0.2,
subset = Type == "TypeB",
col = "orange",
add = TRUE )
Run Code Online (Sandbox Code Playgroud)