เปลี่ยนการวางแนวของเส้นทแยงมุมของพล็อตความสัมพันธ์โดยใช้แพ็คเกจ ggcorrplot - หากพิมพ์บนหรือล่าง

ฉันมีคำถามติดตามผลที่นี่< /ก>.

บุคคลนี้ต้องการสร้างพล็อตความสัมพันธ์กับ ggcorrplot จากแพ็คเกจ ggcorrplot อย่างไรก็ตาม พวกเขาต้องการให้เส้นทแยงมุมลงไปตามเมทริกซ์ แทนที่จะขึ้นจากซ้ายไปขวา ดังนั้น พวกเขาต้องการทำให้กราฟดูเหมือนเมทริกซ์สหสัมพันธ์ที่พวกเขาใช้เป็นอินพุต:

library(ggcorrplot)
data(mtcars)
corr.mat <- cor(mtcars[, c("mpg", "disp", "hp", "drat", "wt", "carb")])
ggcorrplot(corr.mat)
print(corr.mat)

มีการให้วิธีแก้ปัญหาต่อไปนี้ซึ่งใช้ได้ดีตราบใดที่คุณใช้ข้อมูลจำเพาะ type = full อย่างไรก็ตาม หากคุณต้องการแสดงกราฟเพียงครึ่งเดียว มันจะเกิดความยุ่งเหยิง:

# This suggested solution works fine:
ggcorrplot(corr.mat[,6:1])
# The same: 
ggcorrplot(corr.mat[,6:1], type = "full")

# Here we have the problem:
ggcorrplot(corr.mat[,6:1], type = "upper")

ไม่มีใครรู้วิธีสร้างคอร์เรโลแกรมส่วนบนโดยให้เส้นทแยงมุมเปลี่ยนจากซ้ายบนไปขวาล่างอย่างไร


person Poza    schedule 14.05.2021    source แหล่งที่มา
comment
ฉันได้ดูที่ ggorrplot; ดูเหมือนว่าจะมีอยู่ในโค้ดบางบรรทัดที่ทำงานภายใน วิธีที่ง่ายที่สุดคือเปลี่ยนไปใช้แพ็คเกจอื่น (ตามคำตอบของ @elielink) หรือแก้ไขโค้ดพื้นฐาน แต่บางทีฉันอาจจะพลาดอะไรบางอย่างไป   -  person slamballais    schedule 14.05.2021


คำตอบ (2)


คุณสามารถพล็อต corr.mat ด้วย geom_tile ด้วยตนเอง:

library(data.table)
library(ggplot2)
cordt <- as.data.table(corr.mat, keep.rownames = 'col_name')
cordt <- melt(cordt, id.vars = 'col_name', variable.name = 'row_name')

# convert to factor so that rows and columns have the same order as the data
cordt[, row_name := factor(row_name, levels = rev(rownames(corr.mat)))]
cordt[, col_name := factor(col_name, levels = rownames(corr.mat))]

# set diagonal and the top-right half of the matrix to 0 so that those cells appears white
cordt[ncol(corr.mat) - as.integer(row_name) < as.integer(col_name), value := 0]
# remove the last column and the bottom row (where left cells are self correlations only)
cordt <- cordt[as.integer(row_name) < ncol(corr.mat) &
        as.integer(col_name) < ncol(corr.mat)]

ggplot(cordt, aes(x = col_name, y = row_name, fill = value)) +
    geom_tile() +
    scale_fill_gradient2(low = 'blue', high = 'red') +
    labs(x = NULL, y = NULL, fill = 'Corr') +
    theme_minimal()

ป้อนคำอธิบายรูปภาพที่นี่

person mt1022    schedule 14.05.2021

เมื่อฉันต้องการแสดงเพียงครึ่งหนึ่งของเมทริกซ์สหสัมพันธ์ฉันใช้สิ่งนี้ (จากแพ็คเกจ GGally):

ggcorr(mtcars[, c("mpg", "disp", "hp", "drat", "wt", "carb")], method = c('everything', "p"))

อย่างไรก็ตาม เส้นทแยงมุมไม่ได้เป็นสิ่งที่คุณต้องการมากนัก บางทีอาจมีตัวเลือกให้ผกผันมัน

person elielink    schedule 14.05.2021