R:如何使用ggplot2将数据表绘制成特定的顺序?

问题描述 投票:3回答:1

我正在关注this example,我想知道如何绘制具有特定排序的表格。

nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv")
nba$Name <- with(nba, reorder(Name, PTS))
library(ggplot2)
nba.m <- melt(nba)
nba.m <- ddply(nba.m, .(variable), transform, rescale = rescale(value))
(p <- ggplot(nba.m, aes(variable, Name)) + geom_tile(aes(fill = rescale),colour = "white") + scale_fill_gradient(low = "white",high = "steelblue"))
r csv ggplot2
1个回答
3
投票

X和Y变量是交换或删除它们的因素,您只需要处理排除或排序级别的因素。

library(reshape2)
library(ggplot2)
library(plyr)

nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv")

# transform data
nba.m <- melt(nba)
nba.m <- ddply(nba.m, .(variable), transform, rescale = rescale(value))

# basic plot 
p <- ggplot(nba.m, aes(variable, Name, fill = rescale))+
geom_tile(colour = "white")+
scale_fill_gradient(low = "white",high = "steelblue")
print(p)

enter image description here

# reorder levels
# i use smaller dataset for demonstration 
# pick desired rows (players) use : levels(nba.m$Name) to get the full list
desired<-c("Al Jefferson ","Carmelo Anthony ","Chris Paul ",
           "Danny Granger ","Dirk Nowitzki ","Dwyane Wade ",
           "Kevin Durant ","Kevin Martin ","Kobe Bryant ",
           "LeBron James ")
# subset 
nba.m2<-nba.m[nba.m$Name %in% desired,]

# new factor exlcuidng 30 unused levels (players in this case)
nba.m2$Name_new<-factor(nba.m2$Name)

nba.m2$Name_new<-factor(nba.m2$Name_new,ordered = T, levels = c(
  # now we add desired order
  "Al Jefferson ","Kevin Durant ","Kevin Martin ","Kobe Bryant ","LeBron James ",
  "Carmelo Anthony ","Chris Paul ","Danny Granger ","Dirk Nowitzki ","Dwyane Wade "
))

#### remove column levels ( just read your edit)
nba.m2<-nba.m2[nba.m2$variable != "PTS",]

# plot again with new order
p <- ggplot(nba.m2, aes(variable, Name_new, fill = rescale))+
  geom_tile(colour = "white")+
  scale_fill_gradient(low = "white", high = "darkgreen")
print(p)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.