I'm sorry if this a duplicate, but it's un-internet-searchable.
I would like to load ggplot, but without littering my global namespace with all the functions therein.
I am content with accessing the functions as ggplot2::aes(), and I don't want just aes() to work.
In other programming languages, this is the default behaviour.
I think you have really answered this yourself. This works without any library statements as long as ggplot2 is installed:
ggplot2::ggplot(BOD, ggplot2::aes(Time, demand)) + ggplot2::geom_point()
This could alternately be done like this:
ggplot <- ggplot2::ggplot
aes <- ggplot2::aes
geom_point <- ggplot2::geom_point
ggplot(BOD, aes(Time, demand)) + geom_point()
Another possibility is to just temporarily add ggplot2 and then remove it again:
library(ggplot2)
ggplot(BOD, aes(Time, demand)) + geom_point()
detach("package:ggplot2", unload = TRUE)
There are a number of R packages which provide facilities that may be of interest including the modules and import packages on CRAN. Also the klmr modules R package on github (not on CRAN) provides a Python-like framework.
Related
I usually plot my data with the following ggplot syntax:
ggplot(sent.TN.yr.avg, aes(y = (log10(mean)), x = YEAR, color = ECOREGION)) +
geom_point(size = 1, alpha = 0.4) +
geom_smooth(se=TRUE) +
xlab(expression(paste("Year"))) + ylab(expression(paste("Mean TN (", mu, "g", L^-1,")"))) +
theme_light()
But this recently led me to the following loadnamespace(name) error:
Error in loadNamespace(x) : there is no package called ‘labeling’
I'm not sure how this code prompted an error related to "labeling." Still, I tried restarting RStudio and installing that, but it cannot be supported by this version of RStudio (2022.02.3). I also tried the same thing with the "scales" package and got the same result. I've also tried changing the repository to different CRAN mirrors with no success.
Any tips?
Package ggplot2 imports package scales which imports package labeling. So in order to use ggplot you should have installed the other two packages as well.
The version of RStudio most likely has nothing to do with it. But if you recently switched from R version 4.1.* to R4.2.* you have to upgrad all your installed packages (they have to be recompiled after a major R version release).
You can do this in RStudio: Tools -> Check for Package Updates...
or directly in R with: update.packages(checkBuilt = TRUE)
By the way, on the ggplot2 page there is an example of how mathematical expressions can be inserted into axis labels:
https://ggplot2.tidyverse.org/articles/faq-axes.html?q=superscript#how-can-i-add-superscripts-and-subscripts-to-axis-labels
I'm trying to use David Robinson's geom_flat_violin() to make a plot according to the example in this link: https://gist.github.com/dgrtwo/eb7750e74997891d7c20
ggplot(diamonds, aes(cut, carat)) +
geom_flat_violin() +
coord_flip()
If I follow the example I get
Error in geom_flat_violin() : could not find function "geom_flat_violin"
but when I try to copy in his function code, there are several "unexpected ',' " errors and I don't understand what to copy and what to leave behind. Can anyone help?
There are a number of issues with the code listed on the provided link. As the comments in the link suggested, there are some mismatched parenthesis. This can be fixed by removing line 50.
Also, be sure to install the libraries prior to running. This includes the ggplot2, dplyr, and plyr. Typically, they can be installed like so:
install.packages( c( "dplyr", "ggplot2", "plyr" ) )
I was able to run that code after making the fixes listed above.
source( './geom_flat_violin.R' )
ggplot( diamonds, aes( cut, carat ) ) + geom_flat_violin() + coord_flip()
I'm writing a program which has a step involving ggplot2 in R. The plot's relevant steps are:
ggplot() +
geom_violin(data=x, mapping=aes(x=1, y=Mean_cov)) +
geom_jitter(data=x, mapping=aes(x=3, y=Mean_cov, col=Frac_pos)) +
scale_x_discrete(breaks=c(1,3), labels=c("","")) +
scale_y_continuous(limits=c(0, 50)) +
scale_color_gradient2( breaks=seq(0,100,20),
limits=c(0,100),
low="green3", high="darkorchid4",
midpoint=50, name="% covered") +
coord_flip()
Mean_cov and Frac_pos are colnames() of my data.frame(). 1 and 3 are unelegant solutions I found to obtain a plot that separates the geom_jitter() and the geom_violin() by a sufficient space.
This worked in R/3.3.3 but since our sysadmin updated the default R to R/3.5.2 we are experiencing plotting issues (i.e. the plot gets generated but the axes are overlapping the panel margin, instead of being contained within it). I know I could just point it to R/3.3.3 but I would prefer to make my program compatible with newer R versions, since I want to publish it.
The warning I'm getting is quite popular in R-related error threads:
3: In structure(NULL, class = "waiver") :
Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
Consider 'structure(list(), *)' instead.
I am aware of other stackoverflow issues similar to mine, like this one:
R c.Date() raises warning Calling 'structure(NULL, *)' is deprecated
However, I couldn't solve the problem following other issues so I decided to open a new one since it seems to be a ggplot2 issue.
Perhaps the error is raised because of a way ggplot2 calls some function in the background?
Here are 10 lines from my data frame:
Frac_pos Mean_cov
99.78591232934406 42.783034429509
99.98996910484291 24.89770493118806
98.9460737536315 19.48427592934241
99.80868782354266 45.07804411433716
99.48891662209545 88.17287692399121
99.89221021636827 30.86539422141599
99.56238183247297 25.512161961209184
99.00406672752926 32.80431986056934
99.22226325737003 29.72798766048967
This is how it should look like (as with R/3.3.3):
This is how it looks like with newer R versions (see that it is broader? Since I have millions of those dots, many of them fall out of the panel):
I am placing multiple plots into one image using gridExtra::grid.arrange and would like to have the option of saving the combined plot as an object that could be returned from within a function as part of a list of returned objects. Ideally, I would like to do this without printing the plot object.
The code below creates two plots, combines them with grid.arrange, and attempts to save the result into x. However, x evaluates to NULL and the plot is printed. The documentation for grid.arrange points me to arrangeGrob and suggests plotting can be turned off using plot=FALSE, but I get an error when I try that because FALSE is not a grob object.
Any suggestions for what I'm not understanding?
# R under development
# Windows 7 (32 bit)
# ggplot2 1.0.0
# gridExtra 0.9.1
p1 <- ggplot(mtcars, aes(x=factor(cyl), y=mpg)) + geom_boxplot()
p2 <- ggplot(mtcars, aes(x=factor(cyl), y=wt)) + geom_boxplot()
x <- gridExtra::grid.arrange(p1, p2)
x
Per the comments, I'm adding this edit. When I try it with arrangeGrob, I get no output at all.
> gridExtra::arrangeGrob(p1, p2)
> print(gridExtra::arrangeGrob(p1, p2))
Error: No layers in plot
> x <- gridExtra::arrangeGrob(p1, p2)
> x
Error: No layers in plot
The code in your edit does not work properly since you didn't load gridExtra.
library(gridExtra)
y <- arrangeGrob(p1, p2, ncol = 1)
class(y)
#[1] "gtable" "grob" "gDesc"
grid.draw(y)
Edit: since version 2.0.0, my comment about grid dependency below is no longer valid, since grid is now imported.
Edit: With gridExtra version >= 2.0.0, there is no need to attach either package,
p <- ggplot2::qplot(1,1)
x <- gridExtra::arrangeGrob(p, p)
grid::grid.draw(x)
Funny that this was asked so recently - I was running into this problem as well this week and was able to solve it in a bit of a hacky way, but I couldn't find any other solution I was happier with.
Problem 1: ggplotGrob is not found
I had to make sure ggplot2 is loaded. I don't completely understand what's happening (I admit I don't fully understand imports/depends/attaching/etc), but the following fixes that. I'd be open to feedback if this is very dangerous.
if (!"package:ggplot2" %in% search()) {
suppressPackageStartupMessages(attachNamespace("ggplot2"))
on.exit(detach("package:ggplot2"))
}
Somebody else linked to this blog post and I think that works as well, but from my (non-complete) understanding, this solution is less horrible. I think.
Problem 2: no layers in plot
As you discovered too, fixing that problem allows us to use grid.arrange, but that returns NULL and doesn't allow saving to an object. So I also wanted to use arrangeGrob but I also ran into the above error when gridExtra was not already loaded. Applying the fix from problem 1 again doesn't seem to work (maybe the package is getting de-attached too early?). BUT I noticed that calling grid::grid.draw on the result of arrangeGrob prints it fine without error. So I added a custom class to the output of arrangeGrob and added a generic print method that simply calls grid.draw
f <- function() {
plot <- gridExtra::arrangeGrob(...)
class(plot) <- c("ggExtraPlot", class(plot))
plot
}
print.ggExtraPlot <- function(x, ...) {
grid::grid.draw(x)
}
Hooray, now I can open a fresh R session with no packages explicitly loaded, and I can successfully call a function that creates a grob and print it later!
You can see the code in action in my package on GitHub.
I'd like to create a custom Stat object for ggplot2. (Specifically I'd like to create a smoother that works differently than the ones stat_smooth allows- for instance, without a y~x modeling function- but there are other custom Stats I'd like to create even if there were a workaround for my specific case).
I found this suggested solution from Hadley Wickham:
StatExpo <- proto(Stat, {
objname <- "expo"
desc <- "Exponential smoothing"
default_geom <- function(.) GeomLine
calculate_groups <- function(., data, scales, variable="x", ...) {
data$y <- HoltWinters(data$x, ...)
}
})
stat_expo <- StatExpo$new
However, when I try it I get:
Error in proto(Stat, { : object 'Stat' not found
Upon looking around the ggplot code, I found where Stat is defined. However, the Stat object is, as far as I can tell, never exported from ggplot2.
I could write my new stat object within the ggplot2/R folder and then reinstall the package, but obviously this would be cumbersome and make the solution very difficult to share with others. How can I create a custom Stat object outside of the ggplot namespace?
ggplot2:::Stat can be used to access the non-exported object.
getFromNamespace('Stat','ggplot2')