教你快速的使用ggplot2画热图

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.结果展示
教你快速的使用ggplot2画热图_第1张图片

备注:以上代码皆是参考下述链接写成,我只是补充了原作者忘记写的应该library的包
Ref:https://www.r-bloggers.com/ggplot2-quick-heatmap-plotting/

你可能感兴趣的:(教你快速的使用ggplot2画热图)