Movatterモバイル変換


[0]ホーム

URL:


Title:Supporting Graphs for Analysing Time Series
Version:0.2.9
Description:Provides 'ggplot2' graphics for analysing time series data. It aims to fit into the 'tidyverse' and grammar of graphics framework for handling temporal data.
License:GPL (≥ 3)
URL:https://pkg.earo.me/sugrrants/
BugReports:https://github.com/earowang/sugrrants/issues
Depends:ggplot2 (≥ 2.2.0), R (≥ 3.1.3)
Imports:dplyr (≥ 0.8.0), grid, gtable, lubridate (≥ 1.7.1), rlang(≥ 0.2.0)
Suggests:covr, knitr, plotly, readr, rmarkdown, testthat, tidyr,tsibble (≥ 0.8.0), viridis
VignetteBuilder:knitr
Encoding:UTF-8
Language:en-GB
LazyData:true
RoxygenNote:7.2.3
NeedsCompilation:no
Packaged:2024-03-12 00:50:48 UTC; earo
Author:Earo WangORCID iD [aut, cre], Di CookORCID iD [aut, ths], Rob HyndmanORCID iD [aut, ths]
Maintainer:Earo Wang <earo.wang@gmail.com>
Repository:CRAN
Date/Publication:2024-03-12 05:20:03 UTC

sugrrants: supporting graphs for analysing time series

Description

Provides 'ggplot2' graphics for analysing time series data. It aims to fitinto the 'tidyverse' and grammar of graphics framework for handling temporaldata.

Author(s)

Maintainer: Earo Wangearo.wang@gmail.com (ORCID)

Authors:

See Also

Useful links:


Key drawing functions

Description

Key drawing functions

Usage

draw_key_acf(data, params, size)

Arguments

data

A single row data frame containing the scaled aesthetics todisplay in this key

params

A list of additional parameters supplied to the geom.

size

Width and height of key in mm.

Value

A grid grob


Lay out panels in a calendar format

Description

Lay out panels in a calendar format

Usage

facet_calendar(  date,  format = "%b %d",  week_start = getOption("lubridate.week.start", 1),  nrow = NULL,  ncol = NULL,  scales = "fixed",  shrink = TRUE,  dir = "h",  labeller = "label_value",  strip.position = "top")

Arguments

date

A variable that contains dates or an expression that generatesdates will be mapped in the calendar.

format

A character string, such as⁠%Y-%b-%d⁠ and⁠%a (%d)⁠, formattingthe display of facet strips. See?strptime for details.

week_start

Day on which week starts following ISO conventions -1 means Monday (default), 7 means Sunday. You can setlubridate.week.startoption to control this parameter globally.

nrow,ncol

Number of rows and columns defined for "monthly" calendarlayout. IfNULL, it computes a sensible layout.

scales

Should scales be fixed ("fixed", the default),free ("free"), or free in one dimension ("free_x","free_y")?

shrink

IfTRUE, will shrink scales to fit output ofstatistics, not raw data. IfFALSE, will be range of raw databefore statistical summary.

dir

Direction of calendar: "h" for horizontal (the default) or "v" forvertical.

labeller

A function that takes one data frame of labels andreturns a list or data frame of character vectors. Each inputcolumn corresponds to one factor. Thus there will be more thanone withvars(cyl, am). Each outputcolumn gets displayed as one separate line in the striplabel. This function should inherit from the "labeller" S3 classfor compatibility withlabeller(). You can use different labelingfunctions for different kind of labels, for example uselabel_parsed() forformatting facet labels.label_value() is used by default,check it for more details and pointers to other options.

strip.position

By default, the labels are displayed on the top ofthe plot. Usingstrip.position it is possible to place the labels oneither of the four sides by settingstrip.position = c("top", "bottom", "left", "right")

Details

A monthly calendar is set up as a 5 by 7 layout matrix. Each month couldextend over six weeks but in these months is to wrap the last few days upto the top row of the block.

See Also

frame_calendar for a compact calendar display, by quickly transformingthe data.

Examples

fs <- hourly_peds %>%  dplyr::filter(Date < as.Date("2016-05-01"))fs %>%  ggplot(aes(x = Time, y = Hourly_Counts)) +  geom_line(aes(colour = Sensor_Name)) +  facet_calendar(~ Date, nrow = 2) + # or ~ as.Date(Date_Time)  theme(legend.position = "bottom")

Rearrange a temporal data frame to a calendar-based data format using linear algebra

Description

Temporal data of daily intervals or higher frequency levels can be organisedinto a calendar-based format, which is useful for visually presentingcalendar-related activities or multiple seasonality (such as time of day,day of week, day of month). The function only returns a rearranged data frame,andggplot2 takes care of the plotting afterwards. It allows moreflexibility for users to visualise the data in various ways.

Usage

frame_calendar(  data,  x,  y,  date,  calendar = "monthly",  dir = "h",  week_start = getOption("lubridate.week.start", 1),  nrow = NULL,  ncol = NULL,  polar = FALSE,  scale = "fixed",  width = 0.95,  height = 0.95,  margin = NULL,  ...)prettify(plot, label = c("label", "text"), locale, abbr = TRUE, ...)

Arguments

data

A data frame or a grouped data frame including aDate variable.

x

A bare (or unquoted) variable mapping to x axis, for example time ofday. If integer 1 is specified, it simply returns calendar grids on xwithout transformation.

y

A bare (or unquoted) variable or more mapping to y axis. More thanone variable need putting tovars(). If integer 1 is specified, it returnscalendar grids on y without transformation.

date

ADate variable mapping to dates in the calendar.

calendar

Type of calendar. (1) "monthly" calendar (the default) organisesthedata to a common format comprised of day of week in the column andweek of month in the row. A monthly calendar is set up as a 5 by 7 layoutmatrix. Each month could extend over six weeks but in these months is towrap the last few days up to the top row of the block. (2) "weekly"calendar consists of day of week and week of year. (3) "daily" calendarrefers to day of month and month of year.

dir

Direction of calendar: "h" for horizontal (the default) or "v" forvertical.

week_start

Day on which week starts following ISO conventions -1 means Monday (default), 7 means Sunday. You can setlubridate.week.startoption to control this parameter globally.

nrow,ncol

Number of rows and columns defined for "monthly" calendarlayout. IfNULL, it computes a sensible layout.

polar

FALSE (the default) for Cartesian or TRUE for polar coordinates.

scale

"fixed" (the default) for fixed scale. "free" for scalingconditional on each daily cell, "free_wday" for scaling on weekdays,"free_mday" for scaling on day of month.

width,height

Numerics between 0 and 1 to specify the width/height foreach glyph.

margin

Numerics of length two between 0 and 1 to specify the horizontaland vertical margins between month panels.

...

Extra arguments passed togeom_label() andgeom_text()

plot

A "ggplot" object or "plotly".

label

If "label" is specified, it will add month/week text on theggplot object, which is actually passed togeom_label(). If "text" isspecified, it will add weekday/day of month text on theggplot object,which is actually passed togeom_text(). By default, both "label" and"text" are used. If "text2" is specified for the "monthly" calendar only,it will add day of month to theggplot object.

locale

ISO 639 language code. The default is "en" (i.e. US English).For other languages support, packagereadr needs to be installed.Seereadr::locale for more details.

abbr

Logical to specify if the abbreviated version of label should beused.

Details

The calendar-based graphic can be considered as small multiplesof sub-series arranged into many daily cells. For every multiple (orfacet), it requires thex variable mapped to be time of day andy tovalue. Newx andy are computed and named with a. prefixed to variableaccording tox andy respectively, and get ready forggplot2 aestheticmappings. In conjunction withgroup_by(), it allows the grouped variableto have their individual scales. For more details, seevignette("frame-calendar", package = "sugrrants")

Value

A data frame or a dplyr::tibble with newly added columns of.x,.y..xand.y together give new coordinates computed for different types ofcalendars.date groups the same dates in a chronological order, which isuseful forgeom_line orgeom_path. The basic use is⁠ggplot(aes(x = .x, y = .y, group = date)) + geom_*⁠. The variable names.x and.y reflectthe actualx andy with a prefix..

See Also

facet_calendar for a fully-fledged faceting calendar with formallabels and axes.

Examples

library(dplyr, warn.conflicts = FALSE)# compute the calendar layout for the data framecalendar_df <- hourly_peds %>%  filter(Sensor_ID == 13, Year == 2016) %>%  frame_calendar(x = Time, y = Hourly_Counts, date = Date, nrow = 4)# ggplotp1 <- calendar_df %>%  ggplot(aes(x = .Time, y = .Hourly_Counts, group = Date)) +  geom_line()prettify(p1, size = 3, label.padding = unit(0.15, "lines"))# use in conjunction with group_by()grped_calendar <- hourly_peds %>%  filter(Year == "2017", Month == "March") %>%  group_by(Sensor_Name) %>%  frame_calendar(x = Time, y = Hourly_Counts, date = Date, week_start = 7)p2 <- grped_calendar %>%  ggplot(aes(x = .Time, y = .Hourly_Counts, group = Date)) +  geom_line() +  facet_wrap(~ Sensor_Name, nrow = 2)prettify(p2)## Not run: # allow for different languages# below gives simplied Chinese labels with STKaiti font family,# assuming this font installed in user's local systemprettify(p2, locale = "zh", family = "STKaiti")# plotly exampleif (!requireNamespace("plotly", quietly = TRUE)) {  stop("Please install the 'plotly' package to run these following examples.")}library(plotly)pp <- calendar_df %>%  group_by(Date) %>%  plot_ly(x = ~ .Time, y = ~ .Hourly_Counts) %>%  add_lines(text = ~ paste("Count: ", Hourly_Counts, "<br> Time: ", Time))prettify(pp)## End(Not run)

Autocorrelation for temporal data

Description

Since the data input isdata.frame, it's better to sort the date-timesfrom early to recent and make implicit missing values explicit before usinggeom_acf.

Usage

geom_acf(  mapping = NULL,  data = NULL,  position = "identity",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE,  lag.max = NULL,  type = "correlation",  level = 0.95,  ...)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

position

Position adjustment, either as a string naming the adjustment(e.g."jitter" to useposition_jitter), or the result of a call to aposition adjustment function. Use the latter if you need to change thesettings of the adjustment.

na.rm

Logical. IfTRUE, missing values are removed. default is the"correlation" and other options are "covariance" and "partial".

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.borders().

lag.max

An integer indicating the maximum lag at which to calculate theacf.

type

A character string giving the type of the acf to be computed. The

level

A numeric defining the confidence level. IfNULL, no significantline to be drawn.

...

Other arguments passed on tolayer(). These areoften aesthetics, used to set an aesthetic to a fixed value, likecolour = "red" orsize = 3. They may also be parametersto the paired geom/stat.

Examples

library(dplyr)fstaff <- hourly_peds %>%  filter(Sensor_ID == 13)# use ggplot2 fstaff %>%  ggplot(aes(x = ..lag.., y = Hourly_Counts)) +  geom_acf()

Pedestrian counts in Melbourne city

Description

A dataset containing the pedestrian counts at hourly intervals from 2016-01-01to 2017-04-20 at 7 sensors in the city of Melbourne. The variables are as follows:

Usage

hourly_peds

Format

A tibble with 78755 rows and 9 variables:

Date_Time

Date time when the pedestrian counts are recorded

Year

Year associated with Date_Time

Month

Month associated with Date_Time

Mdate

Day of month associated with Date_Time

Day

Weekday associated with Date_Time

Time

Hour associated with Date_Time

Sensor_ID

Sensor identifiers

Sensor_Name

Sensor names

Hourly_Counts

Hourly pedestrian counts

Examples

hourly_peds

Objects exported from other packages

Description

These objects are imported from other packages. Follow the linksbelow to see their documentation.

dplyr

%>%,vars


Autocorrelation for temporal data

Description

Since the data input isdata.frame, it's better to sort the date-timesfrom early to recent and make implicit missing values explicit before usingstat_acf.

Usage

stat_acf(  mapping = NULL,  data = NULL,  geom = "bar",  position = "identity",  na.rm = FALSE,  show.legend = NA,  inherit.aes = TRUE,  lag.max = NULL,  type = "correlation",  level = 0.95,  ...)

Arguments

mapping

Set of aesthetic mappings created byaes(). If specified andinherit.aes = TRUE (the default), it is combined with the default mappingat the top level of the plot. You must supplymapping if there is no plotmapping.

data

The data to be displayed in this layer. There are threeoptions:

IfNULL, the default, the data is inherited from the plotdata as specified in the call toggplot().

Adata.frame, or other object, will override the plotdata. All objects will be fortified to produce a data frame. Seefortify() for which variables will be created.

Afunction will be called with a single argument,the plot data. The return value must be adata.frame, andwill be used as the layer data. Afunction can be createdfrom aformula (e.g.~ head(.x, 10)).

geom

The geometric object to use to display the data, either as aggprotoGeom subclass or as a string naming the geom stripped of thegeom_ prefix (e.g."point" rather than"geom_point")

position

Position adjustment, either as a string naming the adjustment(e.g."jitter" to useposition_jitter), or the result of a call to aposition adjustment function. Use the latter if you need to change thesettings of the adjustment.

na.rm

Logical. IfTRUE, missing values are removed.

show.legend

logical. Should this layer be included in the legends?NA, the default, includes if any aesthetics are mapped.FALSE never includes, andTRUE always includes.It can also be a named logical vector to finely select the aesthetics todisplay.

inherit.aes

IfFALSE, overrides the default aesthetics,rather than combining with them. This is most useful for helper functionsthat define both data and aesthetics and shouldn't inherit behaviour fromthe default plot specification, e.g.borders().

lag.max

An integer indicating the maximum lag at which to calculate the acf.

type

A character string giving the type of the acf to be computed. Thedefault is the "correlation" and other options are "covariance" and "partial".

level

A numeric defining the confidence level. IfNULL, no significantline to be drawn.

...

Other arguments passed on tolayer(). These areoften aesthetics, used to set an aesthetic to a fixed value, likecolour = "red" orsize = 3. They may also be parametersto the paired geom/stat.

Examples

library(dplyr)fstaff <- hourly_peds %>%  filter(Sensor_ID == 13)# use ggplot2 fstaff %>%  ggplot(aes(x = ..lag.., y = Hourly_Counts)) +  stat_acf(geom = "bar")

[8]ページ先頭

©2009-2025 Movatter.jp