我有点惊讶我无法在 SO 上找到解决这个问题的方法,但我已经尝试了我认为可能适用的每个搜索词。但是,我可能没有使用正确的搜索词,所以如果这是重复的,请原谅我,并请指出正确的方向。我有按样本分组的数据,每个样本对每个类别都有一个值,其中有很多。这是一个示例数据框(请注意,样本数量和类别数量通常不同):
df <- data.frame( sample = c( "one", "two", "three", "four" ),
cat_1 = c( 2, 4, -6, 2 ), cat_2 = c( 1, 2, 2, 1 ),
cat_3 = c( 5, -5, 7, 2 ) )
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个图,其中 x 轴具有每个类别的离散点,y 轴是每个类别中所有样本的值,跨类别的每个样本的值由颜色线连接我可以定义。
这似乎ggplot2
是去这里的方式,但我找不到办法让它按照我想要的方式解决。似乎我想colnames( dd )
在使用时成为 x 轴变量,aes()
但这警告我,x
并且y
长度不同。看起来这应该很简单,但我无法弄清楚。
编辑:我遇到过这篇文章Plotting multiple variables from same data frame in ggplot其中答案显示了我想要绘制的确切类型的图,但我不知道如何使用melt
将我的数据框更改为将列名cat_1
, cat_2
, cat_3
, 作为id.vars
.
The function melt
from the reshape2
package, transforms data to long format. It stacks a set of columns into a single column. You may want to define the id variables, which will remain unchanged after calling the function.
If called without arguments, melt
will assume factor and character variables are id variables, and all others are measured. In addition it gives default column names: "variable" and "value". In the result, the old column names are rows under the new column "variable".
library(reshape2)
> melt(df)
Using sample as id variables
sample variable value
1 one cat_1 2
2 two cat_1 4
3 three cat_1 -6
4 four cat_1 2
5 one cat_2 1
6 two cat_2 2
7 three cat_2 2
8 four cat_2 1
9 one cat_3 5
10 two cat_3 -5
11 three cat_3 7
12 four cat_3 2
Run Code Online (Sandbox Code Playgroud)
For your problem, you could use the following code, specifying the id_vars, and specifying more informative column names (the structure remains the same):
df2 <- melt(df, id_vars = sample, variable.name = "category", value.name = "value")
> df2
sample category value
1 one cat_1 2
2 two cat_1 4
3 three cat_1 -6
4 four cat_1 2
5 one cat_2 1
6 two cat_2 2
7 three cat_2 2
8 four cat_2 1
9 one cat_3 5
10 two cat_3 -5
11 three cat_3 7
12 four cat_3 2
ggplot(df2, aes( x=category, y=value, group=sample, col=sample)) +
geom_line()
Run Code Online (Sandbox Code Playgroud)
Please let me know whether this is what you want.