如何使用ggplot2将数据表按特定顺序绘制成图表?

3

我正在参照这个例子,想知道如何按特定排序绘制表格图。

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"))
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接