Giter Club home page Giter Club logo

scales's Introduction

scales scales website

CRAN status R-CMD-check Codecov test coverage

One of the most difficult parts of any graphics package is scaling, converting from data values to perceptual properties. The inverse of scaling, making guides (legends and axes) that can be used to read the graph, is often even harder! The scales packages provides the internal scaling infrastructure used by ggplot2, and gives you tools to override the default breaks, labels, transformations and palettes.

Installation

# Scales is installed when you install ggplot2 or the tidyverse.
# But you can install just scales from CRAN:
install.packages("scales")

# Or the development version from Github:
# install.packages("pak")
pak::pak("r-lib/scales")

Usage

Breaks and labels

The most common use of the scales package is to control the appearance of axis and legend labels. Use a break_ function to control how breaks are generated from the limits, and a label_ function to control how breaks are turned in to labels.

library(ggplot2)
library(dplyr, warn.conflicts = FALSE)
library(lubridate, warn.conflicts = FALSE)

txhousing %>% 
  mutate(date = make_date(year, month, 1)) %>% 
  group_by(city) %>% 
  filter(min(sales) > 5e2) %>% 
  ggplot(aes(date, sales, group = city)) + 
  geom_line(na.rm = TRUE) + 
  scale_x_date(
    NULL,
    breaks = scales::breaks_width("2 years"), 
    labels = scales::label_date("'%y")
  ) + 
  scale_y_log10(
    "Total sales",
    labels = scales::label_number(scale_cut = scales::cut_short_scale())
  )

economics %>% 
  filter(date < ymd("1970-01-01")) %>% 
  ggplot(aes(date, pce)) + 
  geom_line() + 
  scale_x_date(NULL,
    breaks = scales::breaks_width("3 months"), 
    labels = scales::label_date_short()
  ) + 
  scale_y_continuous("Personal consumption expenditures",
    breaks = scales::breaks_extended(8),
    labels = scales::label_dollar()  
  )

Generally, I don’t recommend running library(scales) because when you type (e.g.) scales::label_ autocomplete will provide you with a list of labelling functions to jog your memory.

Advanced features

Scales colour palettes are used to power the scales in ggplot2, but you can use them in any plotting system. The following example shows how you might apply them to a base plot.

library(scales)
# pull a list of colours from any palette
pal_viridis()(4)
#> [1] "#440154FF" "#31688EFF" "#35B779FF" "#FDE725FF"

# use in combination with baseR `palette()` to set new defaults
palette(pal_brewer(palette = "Set2")(4))
par(mar = c(5, 5, 1, 1))
plot(Sepal.Length ~ Sepal.Width, data = iris, col = Species, pch = 20)

scales also gives users the ability to define and apply their own custom transformation functions for repeated use.

# use new_transform to build a new transformation
transform_logp3 <- new_transform(
  name = "logp",
  transform = function(x) log(x + 3),
  inverse = function(x) exp(x) - 3,
  breaks = log_breaks()
)

dsamp <- sample_n(diamonds, 100)
ggplot(dsamp, aes(carat, price, colour = color)) +
  geom_point() + 
  scale_y_continuous(trans = transform_logp3)

scales's People

Contributors

aaronwolen avatar batpigandme avatar billdenney avatar briandiggs avatar clauswilke avatar davidchall avatar dougmitarotonda avatar dpseidel avatar dvmlls avatar hadley avatar jcheng5 avatar jiho avatar jimhester avatar johanneskoch94 avatar jrnold avatar karawoo avatar kohske avatar larmarange avatar lluisramon avatar mikmart avatar mjskay avatar sflippl avatar teunbrand avatar thierryo avatar thomasp85 avatar topepo avatar wch avatar yutannihilation avatar zamorarr avatar zeehio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

scales's Issues

Scales pkg do not install in my 2009 32 bit Mac mini (El Capitan)

I recently upgrade my 2009 Mac mini adding 2gb of ram and installing "El Capitan". For some reason when I try to install "ggplot2" the package Scales ask me for compile it, when I hit yes to continue the process a message appears saying that is unable to compile the dependency. When I check my installed packages the installed Scales version installed is the 0.4.0 and don't allow me to update it to the 0.4.1 version. I try selecting another mirror and installing manually the newer version but it dosen't work. I also install gfortran 4.2.3 and tcltk 8.5.5x11 trying to solve the compiling problem.

The messages that appears are the following:
-"ERROR: compilation failed for package ‘scales’"
-"ERROR: lazy loading failed for package ‘ggplot2’"

I will appreciate any help.

Thanks!

Using `dollar` with a negative number

dollar(3) produces $3 as I would expect, but dollar(-3) produces $-3. I have not generally seen negative dollars written with the negative inside like that, rather, isn't it more common to see -$3?

I looked at your tests for formatter and noticed there were not any tests for negative numbers.

installation of scales failed

I couldn't load the package "tidiverse" because "scales" was missing. Installing the package "scales" failed with the following message:

"devtools::install_github("hadley/scales")
Downloading GitHub repo hadley/scales@master
from URL https://api.github.com/repos/hadley/scales/zipball/master
Installing scales
Installation failed: missing value where TRUE/FALSE needed
Error in if (file.exists(dest) && file.mtime(dest) > file.mtime(lib) && :
missing value where TRUE/FALSE needed"

discard clashes with purrr::discard

I could imagine that other users also run into the following situation

require(purrr)
require(scales)

keggPathways = c("mmu04660", "mmu03060", "mmu04110", "mmu04260", "mmu04723", "mmu05322", "mmu04114")

keggPathways %>% keep(~ .!="mmu04723")
keggPathways %>% discard(~ .=="mmu04723")

keep works as expected, but discard is overloaded by the scales packages and gives an incorrect empty result set.

Namespace conflicts are not really bugs for sure, but it's at least a usability problem since both ggplot2/scales and purrr are likely to be used together.

date_format does not work correctly on hms objects

> library(hms)
> library(scales)
> t <- as.hms(Sys.time())
> date_format("%H:%M", tz="GMT")(t)
[1] "12:30:20.18367"
> format(t, "%H:%M", tz="GMT")
[1] "12:30:20.18367"
> strftime(t, "%H:%M", tz="GMT")
[1] "12:30"

As the function is called "date_format" behaving like "format" is perhaps the right behaviour.

Is this perhaps rather an issue with the hms library which should implement some kind of format method?

tickmark/break calculations with exp_trans, probability_trans fail often

Some ranges seem to break the calculation of the breaks/tickmarks for these transformed axes:
It works for y <- 1:3,  y <- (-10):-7, e.g., but I haven't found an example with more than 4 values that worked ... ?!?

library(ggplot2)
df <- data.frame(x = 1:10)

ggplot(df, aes(x, 1)) + 
  geom_blank() +
  scale_x_continuous(trans = scales::exp_trans())
#> Warning in self$trans$inverse(limits): NaNs produced
#> Error in if (zero_range(as.numeric(limits))) {: missing value where TRUE/FALSE needed

ggplot(df, aes(x, 1)) + 
  geom_blank() +
  scale_x_continuous(trans = scales::logit_trans())
#> Warning in qfun(x, ...): NaNs produced
#> Warning: Transformation introduced infinite values in continuous x-axis

Created on 2019-10-31 by the reprex package (v0.3.0)

Support for currencies other than the dollar

I'm a big fan of the scales package. I've put together some code to use currencies other than the dollar, in particular the euro, sterling, and yen and yuan. It's in a gist. I would love to sit down and build it into a proper extension, with 'styles' and so on, but I don't see that I'll have much time for it in the near future. So while it's grossly incomplete, here is the gist, perhaps someone will feel the urge to complete the sketch I put together.

Among the things I've sketched is specifying a French style that formats numbers differently and that prints the currency symbol after the number instead of before; a UK style for millions/billions units that prints m and bn; a US style that prints M and B, that sort of thing.

https://gist.github.com/annoporci/542fd18fc0551f0706da

Should date_format() pass arguments to format() via `...`?

Currently date_format() only allows one to pass a format argument to format(). This means that attempts to pass tz argument to date_format() generates an error. Could it be rewritten as:

date_format1 <- function(format = "%Y-%m-%d",...){
    function(x) format(x,format,...)
}

`percent` gives NaN% for all values in column if any one is NaN

Supposing I have a tibble with numeric columns y and x and I want to format p = y/x as a percentage, if there are any zero values of x then all values of p = percent(y/x) are NaN% rather than only where x==0. I imagine this is a consequence of the logic that forces constant precision, as mentioned in #76 .

Infelicities with scientific_format()

Re: scientific_format() output vs. comma_format() output

Issue: comma_format()(number) does a better job of outputting scientific notation than scientific_format().

This behavior was triggered while testing graphics examples in the scales package.

Simple examples using comma_format():

comma_format()(1e6)
[1] "1e+06"
comma_format(digits = 6)(1e6)
[1] "1e+06"
comma_format(digits = 7)(1e6)
[1] "1,000,000"

scientific_format()(246493)
[1] "246493"
comma_format()(246493)
[1] "2.465e+05"
comma_format(digits = 6)(246493)
[1] "246,493"

More examples with scientific_format:

scientific_format()(1000)
[1] "1000"
scientific_format()(10000)
[1] "10000"
scientific_format()(100000)
[1] "1e+05"
scientific_format()(230000)
[1] "230000"
scientific_format()(2300000)
[1] "2300000"
scientific_format()(23000000)
[1] "2.3e+07"
scientific_format()(23650000)
[1] "23650000"

It seems a minimum number of trailing digits is necessary to trigger the expected output in scientific_format(). I'll write up some tests using these examples. Similar examples using comma_format():

comma_format()(1000)
[1] "1,000"
comma_format()(4675)
[1] "4,675"
comma_format()(10000)
[1] "1e+04"
comma_format()(12456)
[1] "1.246e+04"
comma_format()(1e5)
[1] "1e+05"
comma_format()(230000)
[1] "2.3e+05"
comma_format()(2300000)
[1] "2.3e+06"
comma_format()(23650000)
[1] "2.365e+07"
comma_format(digits = 8)(23650000)
[1] "23,650,000"

Missing log1p_implementation

Working over my data analysis, I face the need to present a value ranging from 0 to 700 using a log10 transformation. To avoid corrections like add +1 to the var, I decided to check the available transformations and found just what I was looking for in the log1p_trans().
Unfortunately, the function was not yet implement or at least I could not use it. To attend this issue may I propose a small correction using the following code:

log1p_trans <- function(base) {
  trans_new("log1p", function(x) log(x+1,base), function(x) base^x - 1)
}

This piece of code make everything work just fine here and I belive it should help others facing the same issue 👍

why is default `from` c(0, 1) in area palette?

I guess it makes more sense to use the range of sqrt(x) as the default (i.e. the default of rescale), since the data does not have to be in c(0, 1).

area_pal <- function(range = c(1, 6)) {
  function(x) rescale(sqrt(x), range, c(0, 1))
}

Error when non date-times parsed to date/time transformers

From tidyverse/ggplot2#408

library(ggplot2)
library(scales)

to_time2 <- function(x)    structure(x, class = c("POSIXt", "POSIXct"))
from_time2 <- function(x) {
  if (!inherits(x, "POSIXt")) {
    stop("Time transformer requires POSIXt as input", call. = FALSE)
  }
  structure(as.numeric(x), names = names(x))
}
time2_trans <- trans_new("time", "from_time2", "to_time2")

set.seed(123)
d <- data.frame(x=runif(10), y=runif(10))
ggplot(d) + geom_point(aes(x=x, y=y)) + scale_x_continuous(trans = time_trans)
ggplot(d) + geom_point(aes(x=x, y=y)) + scale_x_continuous(trans = time2_trans)

"bendy" linear lines on log2 scale

Sorry of the inarticulate title...

Here is an example where the line that connect points show some bend to them:

dat <- structure(list(C = c(0.25, 0.5, 1, 2, 4), 
                      RMSE = c(0.804624448979835, 0.711270401921118, 
                               0.660698559131119, 0.63020003389642, 
                               0.617379499367643)), 
                 .Names = c("C", "RMSE"), class = "data.frame", 
                 row.names = c(NA, 5L))

ggplot(dat, aes(x = C, y = RMSE)) +  
  geom_point() + geom_line() + 
  coord_trans(x = "log2")

Using scale_y_log10 doesn't show the same issue.

Thanks,

Max

it would be nice to have date_breaks('0.2 sec')

Hi guys,

coming from tidyverse/ggplot2#2120 (comment)

It would be nice if one could define date_breaks with units smaller than 1 second. say 0.5 seconds or the like. Right now, I am doing that manually with

minor_breaks = seq(from = ymd_hms('2000-01-01 08:29:58'), to = ymd_hms('2000-01-01 08:30:10'), by = 0.5)

but this is a pain... What do you think?

Thanks!

Request: Additional argument to percent()

The Commonwealth Style Manual requires that percentages be followed by " per cent", not a % sign.

Request that percent be modified to support this.
eg.
percent(x, sign = "%") { ... }

percent() with zero value yields NaN

> library(scales)
> percent(0.1)
[1] "10%"
> percent(0)
[1] "NaN%"

> sessionInfo()
R version 3.1.0 (2014-04-10)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
[1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
[3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
[5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
[7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
[9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] scales_0.2.4

loaded via a namespace (and not attached):
[1] colorspace_1.2-4 munsell_0.4.2    plyr_1.8.1       Rcpp_0.11.2    

Request: Additional formats

Dear Hadley,
Thanks a lot for your work on this package!

While using it I encountered some problems with formats which might be solved by adding additional format templates.

The "comma_format" command offers a transformation from "1e+05" into "100,000". However, some countries do not use a comma as thousands separator. Instead, for example in Germany a point is used ("100.000"). Is it possible to either add a "point_format" (or similar) which transforms "1e+05" into "100.000"? If this would lead to too much work, could you integrate a format which simply gives the numbers without any transformation ("1e+05" -> "100000").

I have seen the "pull request" "Adding a function unit_format", which could also solve some of my format problems. Is this feature already live? I'm using version 0.2.4 and can't use the unit_format(.) command yet.

Again, thanks a lot for your work!

Best wishes.

PS: As I'm new to GitHub I hope this is the correct way to suggest new features for the package.

Specify the number of rounding places for percent

I have long been a fan of the percent function but there have been instances where I have wanted some more control over the number of rounding places of the output.

This could take a few different forms, so below is a first pass to illustrate the idea. There is almost certainly a better way to formalize the nplaces argument to make it more consistent with the rest of the scales package.

#' @param nplaces The number of decimal places to round the percent.  
#'   For example, nplaces=2 will convert 0.25121 into "25.12%".
percent_format <- function(nplaces = NULL) {
  function(x) {
    if (length(x) == 0) return(character())
    if (is.null(nplaces)) x <- round_any(x, precision(x) / 100)
    else x <- round_any(x, 10^-(nplaces+2))
    paste0(comma(x * 100), "%")
  }
}

Some examples of this change in action:

> percent_format()(.01234567)
[1] "1.23%"
> percent_format(1)(.01234567)
[1] "1.2%"
> percent_format(3)(.01234567)
[1] "1.235%"

What do you think about this addition?

zero_range only checks first two elements in vector

zero_range() compares only the first two numbers in the vector:

> zero_range(c(1,1,6,7))
[1] TRUE

The function is defined as:

zero_range <- function (x) {
    length(x) == 1 || isTRUE(all.equal(x[1] - x[2], 0))
}

But this seems more appropriate:

zero_range <- function (x) {
    length(x) == 1 || isTRUE(all.equal(diff(range(x)), 0))
}

Feature Request: rank_trans

It would make it possible to easily use raw data as plot input, so that Spearman correlation could simply be calculated, because cor needs the raw data as input. For example,

ggplot(plotData, aes(x, y)) + geom_point() + facet_wrap(~ groupID) +
       scale_x_continuous(trans = rank_trans()) + scale_y_continuous(trans = rank_trans()) +
       annotate("text", x = 0, y = 100, hjust = 0, label = paste("r =", round(cor(plotData[, 'x'], plotData[,'y'], method = "spearman"), 2))))

I think it should be in scales, since it seems like a not uncommon use-case.

should percent_format allow variable precision?

I've noticed that when using percent(x), if elements of x are of of different orders of magnitude, percent will pick the precision that works for the largest element.

> percent(c(0.123,0.000234))
[1] "12.3%" "0.0%" 

In other words, precision is constant -- the number of significant figures is not. But sometimes when making a decision tree or a table for a report it's nice to have constant significant figures.

The workaround I currently use is easy enough:

> sapply(c(0.123,0.000234), percent)
[1] "12.3%"  "0.0234%"

to ensure reverse compatibility, maybe something like

percent(x, adjust=FALSE)

where adjust=TRUE would ensure a consistent number of significant figures

Return value too long for empty input to percent, dollar

The return value form each of the formatting functions should be the same length as the input. This is usually true, except that the case with zero length inputs to the percent and dollar functions.

empty_x <- numeric()
percent(empty_x)      #returns "%"
dollar(empty_x)       #returns "$"      

Suggested fixes:

percent <- function (x) 
{
  if(length(x) == 0) return(character())  #This line is new
  x <- round_any(x, precision(x)/100)
  str_c(comma(x * 100), "%")
}

dollar <- function (x) 
{
  if(length(x) == 0) return(character())  #This line is new
  x <- round_any(x, 0.01)
  if (max(x, na.rm = TRUE) < largest_with_cents & !all(x == 
      floor(x), na.rm = TRUE)) {
      nsmall <- 2L
  }
  else {
      x <- round_any(x, 1)
      nsmall <- 0L
  }
  str_c("$", format(x, nsmall = nsmall, trim = TRUE, big.mark = ",", 
      scientific = FALSE, digits = 1L))
}

Tests:

test_that(
  "percent and dollar work with empty input",
  {
    x <- numeric()
    expected <- character()
    expect_identical(percent(x), expected)
    expect_identical(dollar(x), expected)      
  }
)

add asinh_trans to scales

asinh is a commonly used transform especially when the input can be close to zero.

May I request this be added to scales?

Incorrrect scaling with time series data.

I am reposting this bug from ggplot2 because kohske suggested it is caused by the scales packages.

tidyverse/ggplot2#245

The scale issue can be seen with the following command using ggplot2's develop branch:

ggplot(data = data.frame(x = Sys.time() + 1:10, y = rnorm(10)), mapping = aes(x = x , y = y)) + geom_point()

breaks for log scales

> log_breaks(base = 10)(1:1000)
[1]    0  200  400  600  800 1000
> log_breaks(base = 2)(1:1000)
[1]   1   8  64 512

but I expect like this:

> 10^pretty(log10(1:1000), 5)
[1]    1.000000    3.162278   10.000000   31.622777  100.000000  316.227766 1000.000000

log10 with [1, 1000] makes break equally-spaced n original (untransformed) data, while log2 with [1, 1000] in transformed data.
This is because (log10(1000) - log10(1)) / n < 1, but in this case, the threshold is not appropriate.

I'm not sure when this change is useful.

see also this commit: 947f97c

rescale Date (and POSIXct) objects?

Hi,

As of today it is not possible to rescale dates (and times) using scales::rescale. Is there a particular reason? I am puzzled by this, and I think that I must be missing something, because the problem seems fairly simple to tackle (using as.numeric somewhere). I would like to contribute with a clean solution, but I am afraid I am being naive on the solution. Any advice? (ggplot2::geom_segment could benefit from this)

days <- as.Date(c("2016-03-01", "2016-03-02", "2016-03-03"))
scales::rescale(days[2], from = c(days[1], days[3])) == 0.5

datetimes <- as.POSIXct(c("2016-03-01 08:05:00",
                          "2016-03-01 08:10:00",
                          "2016-03-01 08:15:00"),
                        format = "%Y-%m-%d %H:%M:%S")
testthat::expect_equal(scales::rescale(datetimes[2],
                       from = c(datetimes[1], datetimes[3])), 0.5)

I get

Error in Math.Date(x) : abs not defined for "Date" objects

dollar_format and missing data

ggplot() +

  • geom_point(aes(x = carat,y = price),data=diamonds) +
  • scale_y_continuous(labels = dollar_format())
    Error in if (max(x) < 100) 2 else 0 :
    missing value where TRUE/FALSE needed

solution:

dollar_format <- function ()
{
function(x) {
x <- round_any(x, 0.01)
nsmall <- if (max(x, na.rm=TRUE) < 100)
2
else 0
str_c("$", format(x, nsmall = nsmall, trim = TRUE, big.mark = ","))
}
}

scale_x_date or maybe date_format has problems with some dates (e.g. 4-01-31)

With some dates, e.g. dates like 4-01-31 or lower is get the following error message:

Error in charToDate(x) :
character string is not in a standard unambiguous format

Here is an example:

library(ggplot2)
library(scales)


start <- as.Date("100-01-31")
end <- as.Date("200-01-31")
dates <- seq.Date(start, end, by='months')
df <- data.frame(date=dates, value=rnorm(1201))

p <- ggplot(df, aes(date, value)) + geom_point() +
    scale_x_date('\nYEAR AD', 
         breaks = date_breaks("10 years"), 
         labels = date_format("%Y"))
print(p)

start <- as.Date("4-01-31")
end <- as.Date("101-01-31")
dates <- seq.Date(start, end, by='months')
df <- data.frame(date=dates, value=rnorm(length(dates)))
p %+% df  # this fails


start <- as.Date("5-01-31")
end <- as.Date("101-01-31")
dates <- seq.Date(start, end, by='months')
df <- data.frame(date=dates, value=rnorm(length(dates)))
p %+% df  # this works

> sessionInfo()
R version 2.15.1 (2012-06-22)
Platform: i486-pc-linux-gnu (32-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=C                 LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] scales_0.2.1  ggplot2_0.9.1

loaded via a namespace (and not attached):
 [1] colorspace_1.1-1   dichromat_1.2-4    digest_0.5.2       grid_2.15.1
 [5] labeling_0.1       MASS_7.3-18        memoise_0.1        munsell_0.3
 [9] plyr_1.7.1         proto_0.3-9.2      RColorBrewer_1.0-5 reshape2_1.2.1
[13] stringr_0.6

Version 5.0 - Constant Update Available?

Hello:

R constantly identifies Scales as having update to 5.0 available - even after updating. I've removed and reinstalled the package, get the update available as it shows I have version 0.4.1, update appears succesfull, but upon restart it still shows 5.0 is available and that I'm on 0.4.1. Any ideas?

annotate("segment", ...) fails after scale_x_datetime()

Minimal example, adapted from code in help("scale_x_datetime"):

start <- ISOdate(2001, 1, 1, tz = "")
df <- data.frame(
  day30  = start + round(runif(100, max = 30 * 86400)),
  y = seq(1, 100)
)

library(ggplot2)
qplot(day30, y, data = df)
library(scales)
last_plot() + scale_x_datetime(breaks = date_breaks("2 weeks")) 
last_plot() + annotate("segment", x=start, xend=start + 1, y=50, yend=50)

Throws:

Error in Ops.POSIXt((x - from[1]), diff(from)) : '/' not defined for "POSIXt" objects

Unable to find "doColorRamp" function

Hello,
When I try to execute function addPolygons() from package leaflet, I receive the following error:
Error in f(x) : could not find function "doColorRamp"

Such issue only happens if I use the color parameter with a collorPalette:

leaflet::leaflet(nhmap) %>% leaflet::addProviderTiles("CartoDB.Positron") %>% leaflet::addPolygons(stroke=FALSE, smoothFactor = 0.2, fillOpacity = .8, popup = nhpopup, fillColor = ~clintonPalette(nhmap@data$ClintonPct))
I have already used require() and library() functions, but even so the issue persists.

Any help would be great.
Regards,
Cláudio

munsell.map not found

see the examples in seq_gradient_pal():

library(scales)
 x <- seq(0, 1, length = 25)
 show_col(seq_gradient_pal()(x))
 show_col(seq_gradient_pal("white", "black")(x))

the second example does not have any troubles; weird

Using `percent` with a negative number

percent(1) produces 100% as I would expect, but percent(-1) produces NaN% and a warning In precision(x) : NaNs produced.

I noticed you don't have any tests for the percent function.

nice_rgb function missing in new version

i have saved ggplot objects that load during a RNW compile. after updating to new scales version nearly all of them stopped loading due to a missing function in 0.3.0, when i rolled back to 0.2.4 it ran fine.

#running in regular console
> out$plots$p5
Error in scale$palette(uniq) : could not find function "nice_rgb"
In addition: Warning message:
Stacking not well defined when ymin != 0

#running in rnw
Error in scale$palette(uniq) : could not find function "nice_rgb"
Calls: <Anonymous> ... FUN -> scale_map -> scale_map.continuous -> <Anonymous>

(i cant attach the rdata file in this editor) but here is the output in 0.2.4

image

unit_format doesn't recognize NA values

> km <- unit_format(unit = "km", scale = 1e-3, digits = 2)
> km(NA)
[1] "NA km"
> km(NULL)
[1] " km"

I think the output should be NA instead.

One approach could be like this:

unit_format <- function(unit = "m", scale = 1, sep = " ", ...){
  function(x){
    if (is.null(x)) {
      ""
    } else if (is.na(x)) {
      "NA"
    } else {
      paste(comma(x * scale, ...), unit, sep = sep)
    }
  }
}

> km(NA)
[1] "NA"
> km(NULL)
[1] ""

I can create a PR if you think the fix I suggested is OK.

col2hcl makes colours too dark

In the first line of col2hcl, the value should be divided by 255, not 256. For example, col2rgb returns red, green and blue components of 255 for white.

white <- "#ffffff"
t(col2rgb(white))/256
#            red     green      blue
# [1,] 0.9960938 0.9960938 0.9960938

t(col2rgb(white))/255
#      red green blue
# [1,]   1     1    1

EDIT: (fixed black -> white)

add something like `nice_dollar`

I was writing this hack recently

t_dollar <- dollar_format(suffix = 'T')
b_dollar <- dollar_format(suffix = 'b')
m_dollar <- dollar_format(suffix = 'm')
k_dollar <- dollar_format(suffix = 'k')

nice_dollar <- function(x) {
    sapply(x, FUN=function(amount) {
        if (is.na(amount)) return('n.a.')
        if (amount > 9e11) return(t_dollar(amount/1e12))
        if (amount > 9e8) return(b_dollar(amount/1e9))
        if (amount > 9e5) return(m_dollar(amount/1e6))
        if (amount > 9e2) return(k_dollar(amount/1e3))
        dollar(amount)
    })
}

which is useful in scenarios with free scales

image

alpha in scale_fill_manual() apparently not working as expected

Based on this message: http://groups.google.com/group/ggplot2/msg/a94206dc6d6e9b0c, the background rectangles in the examples on pp. 96-97 of the ggplot2 book are not behaving as before in the release version of ggplot2-0.9.0.

Test code:

library('ggplot2')  #v 0.9.0
library('scales')
(unemp <- qplot(date, unemploy, data=economics, geom="line", 
                 xlab = "", ylab = "No. unemployed (1000s)"))

presidential <- presidential[-(1:3), ]

yrng <- range(economics$unemploy)
xrng <- range(economics$date)
unemp + geom_vline(aes(xintercept = start), data = presidential)
unemp + geom_rect(aes(NULL, NULL, xmin = start, xmax = end, fill = party),
                   ymin = yrng[1], ymax = yrng[2],
                   data = presidential) + 
         scale_fill_manual(values = alpha(c("blue", "red"), 0.2))

The last line processes the fill colors but not the transparency, and therefore overwrites the line graph since it is defined last. I don't know if the problem is with scale_fill_manual(), alpha() or their interaction, but the 'quick fix' is to set alpha = 0.2 in geom_rect() and avoid the use of alpha() as the argument for values = in the scale_manual() function. I suspect that alpha is missing as a legal argument in a definition somewhere, but I'm not sure about it.

Dennis

extended_breaks fails if all NA

In reference to:

When ggplot has a facet with all NA values and tries to create a scale (using scales::extended_breaks()) it passes (-Inf, Inf) to labeling::extended() which then fails to create a sane set of breaks and causes an error like:

Error in seq.default(from = best$lmin, to = best$lmax, by = best$lstep) : 'from' must be of length 1

To avoid the error/crash, check for non-finite min/max values in scales::extended_breaks() and return(0) instead of trying to create the breaks with labeling::extended()

i.e. change extended_breaks() to be:

extended_breaks <- function(n = 5, ...) {
  function(x) {
    if (!is.finite(min(x)) || !is.finite(max(x))) return(0)
    labeling::extended(min(x), max(x), n, only.loose = FALSE, ...)
  }
}

patch.txt

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.