tidyr関数を使用answerは最適なソリューションです。もちろん、すでによく知っているreshape2パッケージを使って、必要な結果を得ることができます。
欠けていた重要な要素は、名前とレベルが同じであれば、複数のデータ引数からファセット変数を取得できることです。以下の関数は、データを読み込んだときに動作します(関数定義をスクリプトで最初に使用する前に置いておきたいのですが!)。
plotAccelerometerDataWithPhasesSuperimposed <- function(acceldf, phasesdf) {
# melt the rows for column left/right in order to facet_wrap on it
acceldf_melted <- melt(acceldf[, c('time_ms', 'Ly', 'Ry')],
id.vars = 'time_ms')
# make the facet variables identical
phasesdf$variable <- factor(phasesdf$side, levels = c('Left', 'Right'),
labels = c('Ly', 'Ry'))
ggplot(acceldf_melted, aes(x=time_ms, y=value)) +
# Phases
geom_rect(data = phasesdf, inherit.aes = FALSE, aes(
xmin = acceldf$time_ms[swingStart],
xmax = acceldf$time_ms[heelStrike] - 1,
ymin = -Inf, ymax = Inf, fill = "Swing"), colour = NA, alpha = 0.3) +
geom_rect(data = phasesdf, inherit.aes = FALSE, aes(
xmin = acceldf$time_ms[toeOff],
xmax = acceldf$time_ms[swingEnd] - 1,
ymin = -Inf, ymax = Inf, fill = "Pre-swing"), colour = NA, alpha = 0.3) +
geom_rect(data = phasesdf, inherit.aes = FALSE, aes(
xmin = acceldf$time_ms[heelStrike],
xmax = acceldf$time_ms[toeOff] - 1,
ymin = -Inf, ymax = Inf, fill = "Stance"), colour = NA, alpha = 0.3) +
# Lines
facet_grid(variable~., labeller = labeller(
variable = c(Ly = "Left", Ry = "Right"))) +
labs(title = "Gait Phases by Accelerometer", x = "time (ms)",
y = "Sensors Values") +
geom_line() +
scale_fill_manual('Phases',
values = c('firebrick2', 'orange', 'steelblue2'),
guide = guide_legend()) +
guides(colour = FALSE) +
theme(legend.direction = "horizontal", legend.position = "bottom",
strip.text.y = element_text(size=16, colour = "blue"))
}
あなたは四角形を描画するために使用しているデータフレームは 'Right'で' Left'ファセットとする行くどのデータマーキング 'side'列がある場合は、それが取得するのに十分であるべきデータは正しいファセットに描画されます。 – eipi10
最初のパスでプロットコードを完全に突き止めることができませんでしたが、目立ったのは、 'aes(xmin = acceldf $ time_ms [swingStart]、xmax = acceldf $ time_ms [heelStrike] -1、ymin = -Inf、ymax = Inf、fill = "Swing") '。通常は、データフレーム(特に別のデータフレーム)や 'aes'内のサブセットには名前を付けません。 'data'引数を使って' ggplot'や 'geom_rect'にデータフレームを送り、' aes'の中に裸の変数名を使うだけです。 – eipi10
'aes'の中でサブセットしようとするか、' geom_rect'を複数回呼び出すと、あなたのデータを「より長い」形式に溶かすべきかどうか、あるいは 'geom_rect'を呼び出すことができるように、一度、 'fill 'のような美しいマッピングを使って、異なるグループの異なる色の四角形を取得します。 – eipi10