【问题标题】:Sort groups by specific values in two columns按两列中的特定值对组进行排序
【发布时间】:2017-11-17 00:02:09
【问题描述】:

我想根据 y 轴约为 0.5 的 x 轴值,按每条彩色曲线的顺序对数据集进行排序。现在的图例是基于顺序的。但是,如果您对数据进行正确排序,则图例应类似于 [item 5, item 1, item 3, item 2, item 4]。

library(mirt)
dat <- expand.table(LSAT7)
mod <- mirt(dat, 1)
plt <- plot(mod, type = 'trace', facet_items=FALSE) #store the object
print(plt) #plot the object
str(plt) #find the data
plt$panel.args
pltdata <- data.frame(lapply(plt$panel.args, function(x) do.call(cbind, x))[[1]])
pltdata$item <- rep(colnames(dat), each = 50)


library(ggplot2)
ggplot(pltdata, aes(x, y, colour = item)) + 
  geom_line() + 
  ggtitle('ggplot2 Tracelines') + 
  xlab(expression(theta)) + 
  ylab(expression(P(theta))) + 
  geom_hline(aes(yintercept = 0.5))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    首先,您必须获得与最接近 0.5 的“y”值关联的“x”值(使用 dplyr),然后重新排序“item”变量的级别。

    library(mirt)
    dat <- expand.table(LSAT7)
    mod <- mirt(dat, 1)
    plt <- plot(mod, type = 'trace', facet_items=FALSE) #store the object
    print(plt) #plot the object
    str(plt) #find the data
    plt$panel.args
    pltdata <- data.frame(lapply(plt$panel.args, function(x) do.call(cbind, x))[[1]])
    pltdata$item <- rep(colnames(dat), each = 50)
    
    pltdata$item<-as.factor(pltdata$item)
    library(dplyr)
    aux<-pltdata %>%
      group_by(item) %>%
      slice(which.min(abs(y-0.5)))
    
    aux<-aux[order(aux$x),]
    ord<-as.integer(aux$item)
    pltdata$item = factor(pltdata$item,levels(pltdata$item)[ord])
    
    library(ggplot2)
    ggplot(pltdata, aes(x, y, colour = item)) + 
      geom_line() + 
      ggtitle('ggplot2 Tracelines') + 
      xlab(expression(theta)) + 
      ylab(expression(P(theta))) + 
      geom_hline(aes(yintercept = 0.5))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-16
      • 2021-10-12
      • 1970-01-01
      • 2020-03-08
      • 2016-03-13
      • 2021-09-23
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多