Reputation: 2559
I am following this example and I was wondering how I can graph a table with a specific sorting.
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"))
Upvotes: 3
Views: 1083
Reputation: 368
THe X and Y variables are factors in order to swap or remove them you just have to work with those factor excluding or ordering the levels.
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)
# 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)
Upvotes: 3