このコードは単一のボックスプロットを生成します:
df <- data.frame(value = rnorm(62), my.date = seq(as.Date("2013-12-01"), as.Date("2014-01-31"), by="1 day"))
library(ggplot2)
ggplot(df, aes(as.Date(my.date), value)) + geom_boxplot() + scale_x_date(minor_breaks = "1 week", labels = date_format("%Wn%b"))
12月1日から1月31日までの週ごとに1つのボックスプロットを持つプロットを作成するにはどうすればよいですか?したがって、1つのプロットの中には、約8つのボックスプロットがあるはずです。いずれかを使用するソリューションを好むだろう ggplot()
または scale_x_date()
.
回答:
回答№1は21つの方法は、使用する前に日付を変換することです ggplot
library(ggplot2)
df <- data.frame(value = rnorm(62),
my.date = seq(as.Date("2013-12-01"), as.Date("2014-01-31"), by="1 day"))
weeks <- format(df$my.date, "%Y/%W")
weeks <- factor(weeks, levels = unique(weeks))
ggplot(df, aes(weeks, value)) +
geom_boxplot()
回答№2については2
library(ggplot2)
ggplot(df, aes(format(as.Date(my.date), "%Wn%b"), value)) + geom_boxplot()
編集:
日付を注文するには:
ggplot(df, aes(reorder(format(as.Date(my.date), "%Wn%b"),
as.Date(my.date)),
value)) +
geom_boxplot()
回答№3の場合は0
これは@lucianoの機能を保持する要求を満たす scale_x_date
library("scales")
library(ggplot2)
df <- data.frame(value = rnorm(62), my.date = seq(as.Date("2013-12-01"), as.Date("2014-01-31"), by="1 day"))
ggplot(df, aes(x=as.Date(my.date), y=value, group=format(as.Date(my.date),"%W-%b"))) + geom_boxplot() + scale_x_date(date_breaks = "1 week", date_labels="%Y-%b-%d")
また、データをグループ化したくない場合週# - ほとんどの新年の周りに分割を与える - あなたは週末の日曜日によってグループ化することができます。日曜の週末から金曜日までの調整は、そのようなコードで実現できます
ceiling_date(x, "week") + ifelse(weekdays(x) %in% c("Saturday", "Sunday"), 5, -2)
ggplot(df, aes(x=as.Date(my.date), y=value, group=ceiling_date(my.date, "week"))) + geom_boxplot() + scale_x_date(date_breaks = "1 week", date_labels="%Y-%b-%d")