
R 以 ggplot2 繪製熱圖 Heat Maps 教學與範例
介紹如何在 R 中使用 ggplot2 套件繪製熱圖(heat maps)。 繪製熱圖 若要使用 ggplot 繪製熱圖,可以使用 geom_tile 這個幾何圖案,以下是一個簡單的範例。 library(reshape2) library(ggplot2) # 準備原始資料 x <- data.frame(scale(mtcars)) x$car <- rownames(mtcars) # 將資料表轉為長型表格 x.melt <- melt(x, id.vars = "car") # 使用 ggplot 繪製熱圖 ggplot(x.melt, aes(x = car, y = variable, fill = value)) + geom_tile(colour = "white", size = 0.25) + # 繪製熱圖 scale_y_discrete(expand = c(0, 0)) + # 移除多餘空白 scale_x_discrete(expand = c(0, 0)) + # 移除多餘空白 coord_fixed() + # 設定 X 與 Y 軸等比例 scale_fill_gradientn(colours = terrain.colors(10)) + # 設定色盤 theme( legend.text = element_text(face="bold"), # 說明文字用粗體 axis.ticks = element_line(size=0.5), # 座標軸上的刻度寬度 plot.background = element_blank(), # 移除背景 panel.border = element_blank(), # 移除邊框 axis.text.x = element_text( angle = 90, vjust = 0.5, hjust = 1) # X 軸文字轉向 ) ...



