教你快速的使用ggplot2畫熱圖
阿新 • • 發佈:2019-02-02
1.匯入需要的packages
library(ggplot2)
require(reshape2)
require(scales)
2.匯入資料:
nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv")
nba$Name <- with(nba, reorder(Name, PTS))
> head(nba)
Name G MIN PTS FGM FGA FGP FTM FTA FTP X3PM X3PA X3PP ORB DRB TRB AST STL BLK TO PF
1 Dwyane Wade 79 38.6 30.2 10.8 22.0 0.491 7.5 9.8 0.765 1.1 3.5 0.317 1.1 3.9 5.0 7.5 2.2 1.3 3.4 2.3
2 LeBron James 81 37.7 28.4 9.7 19.9 0.489 7.3 9.4 0.780 1.6 4.7 0.344 1.3 6.3 7.6 7.2 1.7 1.1 3.0 1.7
3 Kobe Bryant 82 36.2 26.8 9.8 20.9 0.467 5.9 6.9 0.856 1.4 4.1 0.351 1.1 4.1 5.2 4.9 1.5 0.5 2.6 2.3
4 Dirk Nowitzki 81 37.7 25.9 9.6 20.0 0.479 6.0 6.7 0.890 0.8 2.1 0.359 1.1 7.3 8.4 2.4 0.8 0.8 1.9 2.2
5 Danny Granger 67 36.2 25.8 8.5 19.1 0.447 6.0 6.9 0.878 2.7 6.7 0.404 0.7 4.4 5.1 2.7 1.0 1.4 2.5 3.1
6 Kevin Durant 74 39.0 25.3 8.9 18.8 0.476 6.1 7.1 0.863 1.3 3.1 0.422 1.0 5.5 6.5 2.8 1.3 0.7 3.0 1.8
3.融合資料:
nba.m <- melt(nba)
> head(nba.m)
Name variable value
1 Dwyane Wade G 79
2 LeBron James G 81
3 Kobe Bryant G 82
4 Dirk Nowitzki G 81
5 Danny Granger G 67
6 Kevin Durant G 74
4.Scale之後列名命名為rescale放入原資料nba.m
nba.m <- ddply(nba.m, .(variable), transform,rescale = rescale(value))
> head(nba.m)
Name variable value rescale
1 Dwyane Wade G 79 0.9473684
2 LeBron James G 81 0.9824561
3 Kobe Bryant G 82 1.0000000
4 Dirk Nowitzki G 81 0.9824561
5 Danny Granger G 67 0.7368421
6 Kevin Durant G 74 0.8596491
5.畫熱圖
p <- ggplot(nba.m, aes(variable, Name)) + geom_tile(aes(fill = rescale),colour = "white") + scale_fill_gradient(low = "white",high = "steelblue")
p
6.結果展示