#' Modify y-axis components
#'
#' Customize the y-axis components for a continuous variable in Datawrapper
#' line, bar and column charts, as well as scatter plots.
#'
#' @param chart_id A string of the Datawrapper chart ID.
#' @param limits A numeric vector of length two to set
#' the lower and upper limits of the axis.
#' @param breaks A numeric vector to set the axis breaks.
#' @param log Defaults to `FALSE`. If `TRUE`, turns the axis into a
#' logarithmic scale.
#' @param position A string to set the axis position. Defaults to `right`.
#' For scatter plots, the argument also accepts `zero` and `off`.
#'
#' @seealso The underlying function: \code{\link[DatawRappr]{dw_edit_chart}}
#'
#' @examples
#' \dontrun{
#' jp_scale_y_c(
#' chart_id = "abcD3",
#' limits = c(0, 200),
#' breaks = seq(0, 200, 40),
#' position = "left"
#' )
#' }
#'
#' @export
jp_scale_y_c <- function(chart_id,
limits,
breaks,
log = FALSE,
position = "right") {
chart_is_compatible <- check_compatibility(chart_id, remove = "bar_charts")
limits_length_two <- dplyr::near(length(limits), 2)
breaks_length_not_one <- length(breaks) > 1
position_line_column_opt <- c("left", "right")
position_scatter_opt <- c("left", "right", "zero", "off")
stopifnot(
chart_is_compatible[["compatibility"]],
is.numeric(limits),
is.numeric(breaks),
limits_length_two,
breaks_length_not_one,
purrr::is_logical(log)
)
chart_type <- chart_is_compatible[["chart_type"]]
chart_is_line <- stringr::str_detect(chart_type, "line")
chart_is_column <- stringr::str_detect(chart_type, "column")
chart_is_scatter <- stringr::str_detect(chart_type, "scatter")
if (chart_is_scatter) {
stopifnot(any(position == position_scatter_opt))
} else {
stopifnot(any(position == position_line_column_opt))
}
if (chart_is_column && log) {
warning("`log = TRUE` does not apply to column charts.")
}
y_axis_components <- if (chart_is_line) {
list(
`y-grid-label-align` = position,
`scale-y` = if (log) {"log"} else {"linear"},
`custom-range-y` = as.list(limits),
`custom-ticks-y` = paste(breaks, collapse = ", ")
)
} else if (chart_is_column) {
list(
yAxisLabels = list(alignment = position),
`custom-range` = limits,
`custom-ticks` = paste(breaks, collapse = ", ")
)
} else if (chart_is_scatter) {
list(
`y-pos` = position,
`y-axis` = list(
log = log,
range = as.list(limits),
ticks = as.list(breaks)
)
)
}
DatawRappr::dw_edit_chart(chart_id = chart_id, visualize = y_axis_components)
chart_metadata_updated <- DatawRappr::dw_retrieve_chart_metadata(chart_id)
invisible(chart_metadata_updated)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.