如何在 R 中制作意大利面图? [英] How to make a spaghetti plot in R?

查看:70
本文介绍了如何在 R 中制作意大利面图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下几点:头(数据框):

I have the following: heads(dataframe):

ID Result Days 

1   70     0         
1   80     23
2   90     15
2   89     30
2   99     40
3   23     24

等等...我想要做的是:用上面的数据创建一个意大利面图.我用的是这个:

ect... what I am trying to do is: Create a spaghetti plot with the above datast. What I use is this:

interaction.plot(dataframe$Days,dataframe$ID,dataframe$Result,xlab="Time",ylab="Results",legend=F) 但没有一条患者线是连续的即使他们应该排很长的队.

interaction.plot(dataframe$Days,dataframe$ID,dataframe$Result,xlab="Time",ylab="Results",legend=F) but none of the patient lines are continuous even when they were supposed to be a long line.

我也想将上面的数据帧转换成这样的:ID 结果天数

Also I want to convert the above dataframe to something like this: ID Result Days

1   70     0         
1   80     23
2   90     0
2   89     15
2   99     25
3   23     0

ect...(我试图取每个 id 的第一个(或最小值),并从零开始计算它们的日期).同样在意大利面图中,我希望所有患者在满足条件时具有相同的颜色,如果不满足条件则使用另一种颜色.

ect... ( I am trying to take the first (or minimum) of each id and have their dating starting from zero and up). Also in the spaghetti plot i want all patients to have the same color IF a condition in met, and another color if the condition is not met.

感谢您的时间和耐心.

推荐答案

这个怎么样,用ggplot2和data.table

How about this, using ggplot2 and data.table

# libs
library(ggplot2)
library(data.table)

# your data
df <- data.table(ID=c(1,1,2,2,2,3),
                 Result=c(70,80,90,89,99,23),
                 Days=c(0,23,15,30,40,24))

# adjust each ID to start at day 0, sort
df <- merge(df, df[, list(min_day=min(Days)), by=ID], by='ID')
df[, adj_day:=Days-min_day]
df <- df[order(ID, Days)]

# plot
ggplot(df, aes(x=adj_day, y=Result, color=factor(ID))) +
  geom_line() + geom_point() +
  theme_bw()

更新后的 data.frame 的内容(实际上是一个 data.table):

Contents of updated data.frame (actually a data.table):

 ID Result Days min_day adj_day
  1     70    0       0       0
  1     80   23       0      23
  2     90   15      15       0
  2     89   30      15      15
  2     99   40      15      25
  3     23   24      24       0

您可以使用 scale_color_manual()

You can handle the color coding easily using scale_color_manual()

这篇关于如何在 R 中制作意大利面图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆