24時間にわたる明条件(つまり、夜間、日の出、昼間、日没)を示すプロットの背景を追加しようとしています。私は、昼と夜のための明るい移行期間(日の出の場合は午前8時〜午後9時、夕方時は午後8時〜午後9時)と無地の色を示すために勾配を使用したいと思います。ggplot2のバックグラウンド用のrasterGrob Rを使用した水平グラデーション
私は非常に近いですが、グラデーションは縦向きであり、水平にする必要があります。
ご協力いただければ幸いです。
現在の作業コード
library(ggplot2)
library(scales)
## date, start and stop time
datestart <- as.POSIXct(strptime('2017-06-20 00:00:00', format = "%Y-%m-%d %H:%M:%S"))
datestop <- as.POSIXct(strptime('2017-06-20 23:59:59', format = "%Y-%m-%d %H:%M:%S"))
## sunrise
risestart <- as.POSIXct(strptime('2017-06-20 08:00:00', format = "%Y-%m-%d %H:%M:%S"))
risestop <- as.POSIXct(strptime('2017-06-20 09:00:00', format = "%Y-%m-%d %H:%M:%S"))
## sunset
setstart <- as.POSIXct(strptime('2017-06-20 20:00:00', format = "%Y-%m-%d %H:%M:%S"))
setstop <- as.POSIXct(strptime('2017-06-20 21:00:00', format = "%Y-%m-%d %H:%M:%S"))
## data limits
lims <- c(datestart, datestop)
## generate some random data
timelist <- seq(datestart, datestop, by = '15 mins')
act <- runif(length(timelist), min = 0, max = 50)
data <- data.frame(timelist, act)
## colours
nightColour <- c("#9ea5ff")
sunriseColour <- c("#9ea5ff", "#fcffbd")
testColour <- c(c("#9ea5ff"), c("#fcffbd"))
dayColour <- c("#fcffbd")
sunsetColour <- c("#fcffbd","#9ea5ff")
## add background
nightGrob <- rasterGrob(nightColour, width = unit(1,"npc"), height = unit(1,"npc"),
interpolate = TRUE)
sunriseGrob <- rasterGrob(sunriseColour, width = unit(1,"npc"), height = unit(1,"npc"),
interpolate = TRUE)
dayGrob <- rasterGrob(dayColour, width = unit(1,"npc"), height = unit(1,"npc"),
interpolate = TRUE)
sunsetGrob <- rasterGrob(sunsetColour, width = unit(1,"npc"), height = unit(1,"npc"),
interpolate = TRUE)
## plot
ggplot(data = data, aes(x = timelist, y = act)) +
annotation_custom(nightGrob, xmin = as.numeric(datestart), xmax = as.numeric(risestart) + 100, ymin = -Inf, ymax = Inf) +
annotation_custom(sunriseGrob, xmin = as.numeric(risestart), xmax = as.numeric(risestop), ymin = -Inf, ymax = Inf) +
annotation_custom(dayGrob, xmin = as.numeric(risestop), xmax = as.numeric(setstart), ymin = -Inf, ymax = Inf) +
annotation_custom(sunsetGrob, xmin = as.numeric(setstart), xmax = as.numeric(setstop), ymin = -Inf, ymax = Inf) +
annotation_custom(nightGrob, xmin = as.numeric(setstop), xmax = as.numeric(datestop), ymin = -Inf, ymax = Inf) +
geom_bar(stat = "identity", colour = "black", fill = "white") +
scale_x_datetime(limits = lims, expand = c(0,0), breaks = date_breaks('1 hour'), labels = date_format(format = "%H", tz = "Europe/London")) +
scale_y_continuous(expand = c(0,0))
色を転置する( 't()') – baptiste
ありがとう!それがトリックでした。 – user3458130