6

私は、ガント チャートの描画に関する自分自身の回答をより一般的なケースに拡張しようとしています。ここで部分的な結果を示します。

Rの年間プランナー

このチャートには多数の移動がプロットされており、赤い点は出発を表し、緑色の点は帰りを表しています。ここに私の課題があります:

  1. 出発から帰国までのすべての日を灰色の点でマークし、他の日はそのままにしておきたいと思います。
  2. ポイントが異なる月の長さを正しくラップすることを望みます (たとえば、6 月 28 日の出発は 6 月 30 日までの日をマークし、7 月 1 日までラップします)。
  3. スクリプトは、1 日の旅行の場合 (たとえば、9 月初旬の旅行で、出発と帰国が同じ日に行われ、小さな緑の点が大きな赤いマーカーにプロットされます) の場合は失敗しません。

以下のコードでこのグラフを作成するのは簡単です。同じ月に両方が発生する赤から緑への線でドットを結合するのは簡単です。閏年や非閏年などにも対応できる一般的な方法でラップアラウンドのケースを手伝ってくれる人はいますか?

library("ggplot2")

# ----------------
# LOAD DATA

df <- read.table(text='id,dep_month,dep_day,ret_month,ret_day
c,1,5,1,16
v,2,1,2,6
a,3,28,3,31
z,4,9,4,11
y,4,25,5,3
f,6,28,7,7
w,8,19,8,29
b,9,9,9,9
k,9,29,10,6
n,11,20,12,3', header = TRUE,
                 sep = ',')

# ----------------
# DRAW YEAR CHART

p <- ggplot(data = df,
            aes(x = dep_day,
                y = dep_month
                )
            )
p <- p + theme_bw()
p <- p + geom_point(colour = 'red',
                    size = 6)
p <- p + geom_point(aes(x = ret_day,
                       y = ret_month
                       ),
                   colour = 'green',
                   size = 4
                    )
p <- p + scale_x_continuous( breaks = c(1:31) )
p <- p + scale_y_reverse( breaks = c(1:12) )
p <- p + ylab("Month") + xlab("Day")
print(p)
4

1 に答える 1

5

おそらく完璧な解決策ではありませんが、オブジェクトを使用すると、はるかに簡単になると思いdateます:

# using your data.frame
# create date object using the dep_month, dep_day etc columns
df$dep.date = as.Date(paste('2012', df$dep_month, df$dep_day, sep='-'))
df$ret.date = as.Date(paste('2012', df$ret_month, df$ret_day, sep='-'))

# calculate the dates for the gray data points between departure and return
# there is probably a more R'ish ways, than a for loop
days <- NULL
for(i in seq(1, nrow(df))){
    tmp <- seq.Date(df[i,]$dep.date, df[i,]$ret.date, by='days')
    days <- rbind(days,
        data.frame(day = as.POSIXlt(tmp)$mday,
            mon = as.POSIXlt(tmp)$mon+1))
}

# plot it
p <- ggplot( days, aes(day, mon)) + geom_point(colour='gray66') + theme_bw() +
 geom_point(data = df, aes(dep_day, dep_month), colour = 'red', size = 6) +
 geom_point(data = df, aes(ret_day, ret_month ),
               colour = 'green', size = 4 )  +
 scale_x_continuous( breaks = c(1:31) ) +
 scale_y_reverse( breaks = c(1:12) ) +
 ylab("Month") + xlab("Day")
print(p)

ここに画像の説明を入力

于 2012-05-10T19:45:35.313 に答える