ggplot "error in rename" - r

update I have posted my solution below, the culprit was my own rename function that overrode reshape::rename
I have been using the ggplot R package with little trouble until today. Today, I get an error using code that has previously worked, and when I debug it to the minimal working example, it still gives an error;
If I do this:
library(ggplot2)
d<- data.frame(x=1:3,y=1:3)
ggplot(data=d) + geom_line(aes(x,y))
The following error is returned:
Error in rename(x, .base_to_ggplot) :
unused argument(s) (.base_to_ggplot)
The traceback is:
6: rename(x, .base_to_ggplot)
5: rename_aes(aes)
4: aes()
3: structure(list(data = data, layers = list(), scales = Scales$new(),
mapping = mapping, options = list(), coordinates = CoordCartesian$new(),
facet = FacetGrid$new(), plot_env = environment), class = "ggplot")
2: ggplot.data.frame(data = d, aes = c(x, y))
1: ggplot(data = d, aes = c(x, y))
The error does not occur after removing all objects using rm(list=ls()), but it is still not clear to me what object is causing this error or why - how can I figure this out?
Does anyone know what may have gone wrong?

I'm not able to return the same error message that you've posted above. When running your code snippet, I'm getting the following error:
Error: geom_pointrange requires the following missing aesthetics: ymin, ymax
Accordingly, geom_pointrange() is expecting arguments for ymin and ymax. I'll leave it up to you to fill in your pertinent information for what should go into those parameters, but this code executes:
ggplot(data=d) + geom_pointrange(aes(x,y, ymin = y - .5, ymax = y + .5))

The problem is caused because ggplot2 doesn't use namespaces - this will be fixed in the next release.

The error was caused by one of the objects (thanks to pointers from #Chase).
Here is how I debugged and found the culprit. The important part was to use the try() function that keeps the for loop running despite errors
foo <- ls() #get a static list of all suspect objects
for(i in 1:length(foo)) {
print(foo[i])
rm(list=foo[i])
try(ggplot()+geom_point(aes(x=1:2,y=1:2)))
}
This resulted in the following output:
...
[1] "45 reg.model"
Error in rename(x, .base_to_ggplot) :
unused argument(s) (.base_to_ggplot)
[1] "46 reg.parms"
Error in rename(x, .base_to_ggplot) :
unused argument(s) (.base_to_ggplot)
[1] "47 rename"
[1] "48 samples"
...
aha! it was my own function rename that caused the error, since ggplot2 relies on reshape::rename.
Solution: rename the new rename function... how to prevent this in the future? Perhaps study up on the use of namespaces.

Related

ggplot2 in R -- error message and then also no points being plotted

I am working on my data analytics cert (google) on Coursera and there is a hands on activity with ggplot.
It tells me to type this:
ggplot(data = penguins) + geom_point(mapping = aes(x = flipper_length_mm, y = body_mass_g))
into the console, so I did and got this error message:
Error in draw_axis(break_positions = guide$key[[aesthetic]], break_labels = guide$key$.label, :
lazy-load database '/home/rstudio-user/R/x86_64-pc-linux-gnu-library/4.0/gtable/R/gtable.rdb' is corrupt
In addition: Warning messages:
1: Removed 2 rows containing missing values (geom_point).
2: In draw_axis(break_positions = guide$key[[aesthetic]], break_labels = guide$key$.label, :
restarting interrupted promise evaluation
3: In draw_axis(break_positions = guide$key[[aesthetic]], break_labels = guide$key$.label, :
internal error -3 in R_decompress1
When I then put quote marks around the column names, I at least got what looks like a plot, but absolutely no points on the graph. I tried with different col names, because maybe something isn't a number? but that didn't matter, nothing happens with the plot.
Coursera is not really a whole lot of help, and I've been trying to get help from others in the course (since I'm taking it thru an organization) but haven't been able to get any help. Is there someone out there who sees what I'm doing wrong?

Creating a Line Graph using ggplot

I am brand new at using R code. I am trying to produce a line graph. Here is my code:
ggplot(data = legosets, mapping = aes(x = num_sets, y = Year)) +
geom_line()
Unfortunately it is producing an error which reads
Error in FUN(X[[I]], ...) : object 'num_sets' not found Calls: ... -> f -> scales_add_defaults -> apply -> FUN execution halted
Any idea how to fix this?
Assuming this is about the legosets data in the lego package : https://github.com/seankross/lego/blob/master/data-tidy/legosets.csv
You can find the variables in there here: https://www.rdocumentation.org/packages/lego/versions/0.1.1/topics/legosets
I assume you need to replace num_sets by Pieces, but you need to read the variable dexcription yourself to confirm that.

I keep getting the same error no matter what from R library rWBclimate

I am trying to use the package "rWBclimate", but nothing works and I keep getting the same error message.
Even when I try running code from the vignette (see code below) I get the same error
(https://cran.r-project.org/web/packages/rWBclimate/vignettes/rWBclimate.pdf).
I have tried several functions and I have fiddled around with the UTF-settings, I have also updated R and all packages to the latest versions...
library(rWBclimate)
usa.dat <- get_model_temp("USA", "mavg", 2080, 2100)
usa.dat.bcc <- usa.dat[usa.dat$gcm == "bccr_bcm2_0", ]
usa.dat.had <- usa.dat[usa.dat$gcm == "ukmo_hadcm3", ]
usa.dat.bcc$ID <- paste(usa.dat.bcc$scenario, usa.dat.bcc$gcm, sep = "-")
usa.dat.had$ID <- paste(usa.dat.had$scenario, usa.dat.had$gcm, sep = "-")
plot.df <- rbind(usa.dat.bcc, usa.dat.had)
ggplot(plot.df, aes(x = as.factor(month), y = data, group = ID, colour =
gcm, linetype = scenario)) + geom_point() + geom_path() + ylab("Average
temperature in degrees C \n between
xlab("Month") + theme_bw()
Error = "No encoding supplied: defaulting to UTF-8.
Error in rep(locator, dim(data_out)[1]) : invalid 'times' argument"
Any suggestions?
Thank you
The encoding is not the problem here, that is not an error message.
When running vignette this is what pops up for me:
No encoding supplied: defaulting to UTF-8.
Error in rep(locator, dim(data_out)[1]) : invalid 'times' argument
The first bit is FYI - R is telling you it defaults to UTF-8.
Check the description file in the package of for example tidyverse, ggplot, caret. You will observe that there is a line reading:
Encoding: UTF-8.
In the description file of the package rWBclimate the encoding is missing which I reckon is prompting R's message.
The second bit is the error and I suspect the issue is with the package itself as a quick glance shows some of the functions are not visible to R, ie. check_ISO_codes() returns an error: could not find function "check_ISO_code". I am not entirely sure if the code is even maintained anymore, there were some questions about its status:
https://github.com/ropensci/rWBclimate/issues/35
If I understand correctly the maintenance was shifted but I am not sure if the package has since been updated in any way.
In any case, hope you get to the bottom of this!

cbind on ggplotGrob objects fails with "Error in mmm < each : comparison of these types is not implemented"

This appears to be similar to an issue that #baptiste was trying to work around back in 2014. I am revisiting code I wrote back in June that involved creating three ggplotGrobs and combining them with a call to cbind. Now, this code fails with the message: "Error in mmm < each : comparison of these types is not implemented."
I thought that this would be specific to my particular application, but I was able to make a very simple, reproducible example. Even if the cbind is performed on two identical ggplotGrobs, this code still fails.
library(ggplot2)
library(gtable)
# Make some plots
pl1 <- ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point()
pl2 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
geom_point()
# Convert to grobs
pl1_grob <- ggplotGrob(pl1)
pl2_grob <- ggplotGrob(pl2)
# Bind them together -- Error!
combined_grob <- cbind(pl1_grob, pl2_grob)
The error and relevant traceback are here:
> combined_grob <- cbind(pl1_grob, pl2_grob)
Error in mmm < each : comparison of these types is not implemented
> traceback()
8: comp(x_val, y_val)
7: unit(comp(x_val, y_val), x_unit)
6: compare_unit(x$heights, y$heights, pmax)
5: cbind_gtable(x, y, size = size)
4: f(init, x[[i]])
3: Reduce(function(x, y) cbind_gtable(x, y, size = size), gtables)
2: cbind(deparse.level, ...)
1: cbind(pl1_grob, pl2_grob)
This code fails with R-3.4.2 on OS X 10.11.6 with grid_3.4.2, gtable_0.2.0, and ggplot2_2.2.1, AND with R-3.3.2 on Linux (compiled from source on Ubuntu 16.04) with grid_3.3.2, gtable_0.2.0, and ggplot2_2.2.1.
Before making the example above, I noticed that one of the vignettes in the "lemon" package ("gtable_show_lemonade") fails near the very end with the same error upon a cbind of two gtables. I confirmed this error by running the code for this vignette from source, which goes something like:
library(lemon)
edit(vignette('gtable_show_lemonade', package = 'lemon'))
# Then use whichever editor you opened to copy the temporary filename
# of the vignette source, and run this with source()
The compiled vignette (with failed cbind) is here: https://cran.r-project.org/web/packages/lemon/vignettes/gtable_show_lemonade.html
The failure during vignette compilation was obtained using the aforementioned R-3.4.2 instance running on OS X 10.11 (El Capitan).
I would appreciate any help with working around this! Since I would like to use my Mac to generate the figures (better font situation), I'm hoping there is a way I can overload a function to fix this.
UPDATE:
This is "only" a problem if size = 'max', which is the default, is specified (or size = 'min'). I think that I can work around it using size = 'first' or size = 'last', which do not perform the offending height comparisons, but it is certainly not convenient that the default behavior doesn't work (and there are certain situations size = 'max' is useful).
I never managed to get this fixed in gtable so gridExtra has a modified version called gtable_cbind.

How to suppress qplot's binwidth warning inside a function?

I am writing a function that uses qplot() to draw a histogram, for example,
> library(ggplot2)
> d=rnorm(100)
> myfun=function(x) qplot(x)
Running it gives a warning:
> myfun(d)
stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
To suppress the warning, I tried computing the binwidth myself, but this gives an error and doesn't plot:
> myfun=function(x) print(qplot(x, binwidth=diff(range(x))/30))
> myfun(d)
Error in diff(range(x)) : object 'x' not found
I have two related questions:
What is going on here? Why is object 'x' not found?
How can I write the function so the warning is not generated?
Thanks!
To attempt to clear up some confusion, this construct does not prevent the binwidth warnings/messages to appear:
suppressMessages(p <- ggplot(...))
print(p)
But this does:
p <- ggplot(...)
suppressMessages(print(p))
As Hadley's comment points out, lazy evaluation prevents the stat_* functions from actually running until they need to at print-time.
I can't explain the why of this one (Hadley may swing by and do so) but using ggplot instead of qplot solves the problem:
d <- data.frame(v1 = rnorm(100))
myfun <- function(x){
p <- ggplot(data = x, aes(x = v1)) +
geom_histogram(binwidth = diff(range(x$v1))/30)
print(p)
}
Doing it this way I get no warning message. Also, using ggplot and removing the binwidth = ... portion in geom_histogram makes the warning reappear, but then suppressMessages works as expected as well.
I suspect this has to do with namespaces or environments and when/where qplot and ggplot are evaluating arguments. But again, that's just a guess...
As they say on TV "Had this been a real warning you would have been given directions from your local authorities."
Since it wasn't a warning then my original answer didn't cause it to error out. This is what I should have written:
options(warnings= -1)
<do something> # no warnings
options(warnngs=1)
<business as usual>
But it wasn't a warning but a message to the console. Here's how to stop it:
con=file("temp.fil", "w")
sink(con, type="message")
library(ggplot2)
d=rnorm(100)
myfun=function(x) qplot(x)
myfun(d)
sink( type="message")

Resources