简体   繁体   English

以一个变量为参考在x轴上排序数据

[英]Sorting data on x-axis taking one variable as reference

Hello I think that this must be something stupid, but I am stuck.. 您好,我认为这一定是愚蠢的,但是我被困住了。

I have 5 participants and two task 我有5名参与者和两项任务

participant<-1:5
scoreA<- c(20, 18, 19, 15,16)
scoreB<- c(4, 2, 6, 1,3)

I create a data frame and I sort it using the variable scoreA as reference 我创建一个数据框,并使用变量scoreA作为参考对其进行排序

total<- data.frame(scoreA, scoreB, participant)
total <- total[order(total[,1]),]

Because I want to create a graph line using ggplot I melt the data and try to do the graph: 因为我想使用ggplot创建一条图形线,所以我将数据融化并尝试绘制图形:

totalM <- melt(total, id="participant", measured= c("scoreA", scoreB))
ggplot(totalM, aes(participant, value, shape= variable, linetype=variable))+geom_point(size=5)+geom_line(size=1)

I don't understand the reason why I don't see in the graph the data sorted using the variable scoreA as reference. 我不明白为什么我在图表中看不到使用变量scoreA作为参考排序的数据的原因。 Any idea? 任何想法? How can I do this? 我怎样才能做到这一点?

Did you want something like this? 你想要这样的东西吗?

在此处输入图片说明

# Convert participant to a factor, with order given by the scoreA variable
# from your "total" data frame
totalM$participant <- factor(totalM$participant,
                             levels=arrange(total, scoreA)$participant)

# Plot!
ggplot(totalM, aes(participant, value, shape= variable, linetype=variable)) +
  geom_point(size=5)+
  geom_line(aes(x=as.numeric(participant)), size=1)
# Note the last geom, I modified the aes

Basically, I make the participant variable a factor, ordered by scoreA . 基本上,我使participant变量成为一个因子,由scoreA Then ggplot will plot the participant variable in the given factor order. 然后, ggplot将按照给定的因子顺序绘制participant变量。 One little adjustment I had to make to force ggplot to plot the lines is to grab the numeric value of the factor for the participant variable for geom_line . 为了使ggplot绘制线,我必须进行一些小的调整,以获取geom_line participant变量的因子的数值。

This is the first thing that came to mind. 这是我想到的第一件事。 Maybe there is a better way to do this? 也许有更好的方法可以做到这一点?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM