【问题标题】:R: How to graph a data table into a specific order with ggplot2?R:如何使用 ggplot2 将数据表绘制成特定顺序?
【发布时间】:2018-05-30 17:49:15
【问题描述】:

我正在关注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】:

    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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 2021-02-10
      • 2021-03-17
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      相关资源
      最近更新 更多