我有以下数据:
df <- data.frame(ID=c(1,1,1,1,2,2,3,3,4,4,4,4,5,5,5,6,6,6,6),
task=c("p","p","p","p","p","b","p","b","p","p","b","b","b","p","p","b","b","p","p"),
value=c(0.3,0.29,0.33,0.33,0.11,0.4,0.15,0.49,0.11,0.4,0.32,0.59,0.6,0.4,0.53,0.63,0.44,0.52,0.55),
value2=c(110.7,68.96,122.31,125.91,21.1,160,43.3,136,NA, NA, NA, NA, 195,216,NA, 21.87,27.62,19.43,20.48),
data_type=c("value","value","value","value","value","value","value","value","from","to","from","to","value","value","value","from","to","from","to")
)
我想在x轴上绘制ID
,然后在y轴上绘制value
和value2
,然后将facet wrap与task一起使用,以便创建2个图在条件task
下。
我正在努力的是不同的数据类型。例如,ID = 1具有可以用geom_line
显示的范围的最小值和最大值,而其他ID只有可以用geom_poin
显示的单个值。另外,每个ID都有value
和value2
,它们的范围非常不同。
如何用ggplot平滑地绘制数据?
答案 0 :(得分:1)
一种选择是将数据重整为长格式,然后以可以使用自由y轴的方式进行构面。
library(data.table)
library(ggplot2)
df <- data.frame(ID=c(1,1,1,1,2,2,3,3,4,4,4,4,5,5,5,6,6,6,6),
task=c("p","p","p","p","p","b","p","b","p","p","b","b","b","p","p","b","b","p","p"),
value=c(0.3,0.29,0.33,0.33,0.11,0.4,0.15,0.49,0.11,0.4,0.32,0.59,0.6,0.4,0.53,0.63,0.44,0.52,0.55),
value2=c(110.7,68.96,122.31,125.91,21.1,160,43.3,136,NA, NA, NA, NA, 195,216,NA, 21.87,27.62,19.43,20.48),
data_type=c("value","value","value","value","value","value","value","value","from","to","from","to","value","value","value","from","to","from","to")
)
setDT(df)
setnames(df, "value", "value1")
df.long <- melt(df, measure.vars=c("value1","value2"))
ggplot(df.long, aes(x=ID, y=value)) + geom_point() + facet_grid(variable~task, scales="free_y")