[英]Plotting multi-dimensions of data using ggplot2
我在下面提到了目錄結構:
Folder named A contains txt files named 1, 2, 3, .., 5
Folder named B contains txt files named 1, 2, 3, .., 5
|
--A (Folder)
|---1.txt
|---2.txt
....
|---5.txt
--B (Folder)
|---1.txt
|---2.txt
....
|---5.txt
我正在通過2個嵌套的for循環將這些文本文件讀入數據幀。 單個數據幀如下所示:
df <- data.frame(Comp.1 = c(0.3, -0.2, -1, NA, 1),
Comp.2 = c(-0.4, -0.1, NA, 0, 0.6),
Comp.3 = c(0.2, NA, -0.4, 0.3, NA))
row.names(df) <- c("Param1", "Param2", "Param3", "Param4", "Param5")
值始終在-1和+1之間。 所有這些數據幀的行數(參數)和列數(組件)不相同。 例如:上述數據幀為3x5,其他數據幀可以為5x15、4x10、5x40等。
我想要一個具有以下內容的情節:
1. parameters on x-axis
2. components on y-axis
3. values as points in the above graph
4. shape of point representing folder name (A = square, B = triangle, C = circle, .., E)
5. color inside the point shape representing file name (1, 2, 3, .., 5)
6. color intensity describing value (For eg: light red [almost white] color representing closer to -1 like -0.98, dark red representing closer to 1 like 0.98)
我有以下代碼:
alphabets = c("A", "B", "C", "D", "E", "F")
numbers = c(1, 2, 3, 4, 5)
pca.plot <- ggplot(data = NULL, aes(xlab="Principal Components",ylab="Parameters"))
for (alphabet in alphabets){
for(number in numbers){
filename=paste("/filepath/",alphabet,"/",number,".txt", sep="")
df <- read.table(filename)
#Making all row dimensions = 62. Adding rows with NAs
if(length(row.names.data.frame(df))<62){
row_length = length(row.names.data.frame(df))
for(i in row_length:61){
new_row = c(NA, NA, NA, NA, NA, NA)
df<-rbind(df, new_row)
}
}
df$row.names<-rownames(df)
long.df<-melt(df,id=c("row.names"), na.rm = TRUE)
pca.plot<-pca.plot+geom_point(data=long.df,aes(x=variable,y=row.names, shape = number, color=alphabet, size = value))
}
}
編輯:按照@Gregor在評論中提到的步驟之后,我有一個big_data_frame像這樣: head(big_data, 3)
Comp.1 Comp.2 Comp.3 Comp.4 Comp.5 params alphabet number 1 NA NA NA NA NA param1 A 1 2 NA NA NA 0.89 NA param2 A 1 3 NA -0.95 NA NA NA param3 A 1
您需要melt
數據框以折疊所有Comp
列。 其他列應保持不變:
long_data = reshape2::melt(
big_data,
id.vars = c("params", "alphabet", "number"),
variable.name = "comp",
value.name = "value",
na.rm = T
)
現在,您的大多數要求都很簡單:
- x軸上的參數
- y軸上的分量
- 上圖中作為點的值
- 代表文件夾名稱的點的形狀(A =正方形,B =三角形,C =圓形,..,E)
- 表示文件名的點形狀內的顏色(1、2、3,..,5)
- 顏色強度描述值(例如:淺紅色[接近白色]顏色表示接近於-1,如-0.98,深紅色表示顏色接近於1,如0.98)
ggplot(long_data, aes(
x = params, y = comp, size = value,
shape = folder, color = factor(number), alpha = value
)) +
geom_point()
棘手的部分是對顏色強度和整體顏色的要求。 我知道使用標准ggplot
對此進行近似的唯一方法是像上面一樣使用透明度。 這是在此問題中采用的方法 。
請注意,這是未經測試的,因為您的數據沒有可復制的共享。 如果存在需要測試的問題,請按照注釋中的建議與dput
共享數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.