ggplot graphs appearing empty when using Rmarkdown - r

I am having problems using ggplot with Rmarkdown.
I have a code that is supposed to return a ggplot graph.When I execute the code in a R session it works but the same code returns an empty plot when using R markdown.This is the code I am using in the R session
m<-ggplot(data=t,aes_string(x=v,y =t$cnt_pct))
m+geom_bar(stat = "identity",fill="#FF0000",color='black')+geom_text(aes(label = cnt_pct),vjust=-0.2)+ggtitle(paste(v,paste("graph")))+theme(plot.title = element_text(hjust = 0.5))+ylab("percent")+geom_line(aes_string(x=v,y =t$keshel_pct),group=1,size=2)
This is the code I am using in the Rmarkdown
m<-ggplot(data=t,aes_string(x=v,y =t$cnt_pct))
m+geom_bar(stat = "identity",fill="#FF0000",color='black')+geom_text(aes(label = cnt_pct),vjust=-0.2)+ggtitle(paste(v,paste("graph")))+theme(plot.title = element_text(hjust = 0.5))+ylab("percent")+geom_line(aes_string(x=v,y =t$keshel_pct),group=1,size=2)
plot(m)
The only diffrence between the two is that with the Rmarkwond a plot(m) line is added.
For some reason the plot command makes the graph empty, when I remove it and run the Rmarkdown no graphs are returned.
This is the graph empty
This is the graph working in a session of R
Anybody has any idea what is my mistake?
Any help will be appriciated

You have a few issues here:
1) your plot syntax has issues. aes_string takes strings referring to column names, but you're passing a variable v for x and direct column data t$cnt_pnt for y. Check some ggplot examples to get the syntax right.
2) The plot(m) statement shouldn't work for two reasons: first, you print ggplot objects, not plot them. Second, you are not assigning the m + geom_bar(...) statement to anything, so even if your plot statement did work, you'd get the plot without the geom_bar(...) stuff. Try e.g. y = m+ geom_bar(...); print(y) instead.

Related

ggplot error in if (node$tag == "span") after trying to split a faceted plot over multiple pages

My dataset includes the variable "annual_TRW" measured over different "survey_year", with 5 "Sample_Core_ID" within each "block" nested within each "site".
The following code was working to plot all samples for a plot subset.
pdf("plots.pdf")
library(ggplot2)
dataset %>%
group_by(site, block, Sample_Core_ID ) %>%
ggplot(., aes(x = survey_year, y = annual_TRW, colour = Sample_Core_ID)) +
geom_line() +
facet_grid(Sample_Core_ID ~ .)
dev.off()
Then, I was trying to split a faceted plot over multiple pages, with each page including the faceted plots (1 column, 5 rows) corresponding to the samples of each block. I was testing using different different functions ggplus::facet_multiple, gridExtra::marrangeGrob, and ggforce::facet_wrap_paginate, but without success i.e. pdf were created empty.
The problem is that, after trying different options, now I get the following error every time that I try to use any ggplot on the same dataset. Now, I dont manage to plot the code that worked before without giving this error.
Error in if (node$tag == "span") { : argument is of length zero
Question 1: How can I solve this error every time I try to use this ggplot?
Question 2: Once this works again, how can I split the faceted plot over multiple pages as explained before?
Thanks a lot in advance!
I tried re-running the entire code, and re-calling the packages, but it doesnt work.
Regarding Problem 1: the error was solved after updating the R version and reinstalling only the necessary packages that worked. The issue might have come from installing the packages ggplus as described here https://github.com/guiastrennec/ggplus

grid.arrange() output adding blank space and extra plot in R Markdown

I am struggling to figure out how to plot two transform() (dlookr library) plots together nicely in R Markdown. The following code results in the output from the picture included with this post. I want the last plot (2x2) and am wondering why the other two are populating as well. How can I only print the last one in Markdown?
# payment transformation
payment_log <- transform(my_data$payment, method = "log")
# income transformation
income_log <- transform(my_data$income, method = "log")
grid.arrange(
plot(payment_log,typographic=FALSE), # visual of transformation
plot(income_log,typographic=FALSE), # visual of transformation
ncol=1)
The first two plots can be avoided by wrapping each plot in a function call inside as.grob, and then passing these variables to grid.arrange.
library(dlookr)
library(ggplotify)
my_data=data.frame(payment=c(1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9),
income=c(1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9))
payment_log=transform(my_data$payment, method="log")
income_log=transform(my_data$income, method="log")
x=as.grob(function() plot(payment_log))
y=as.grob(function() plot(income_log))
grid.arrange(grobs=list(x,y), ncol=1)

Ggplot does not show plots in sourced function

I've been trying to draw two plots using R's ggplot library in RStudio. Problem is, when I draw two within one function, only the last one displays (in RStudio's "plots" view) and the first one disappears. Even worse, when I run ggsave() after each plot - which saves them to a file - neither of them appear (but the files save as expected). However, I want to view what I've saved in the plots as I was able to before.
Is there a way I can both display what I'll be plotting in RStudio's plots view and also save them? Moreover, when the plots are not being saved, why does the display problem happen when there's more than one plot? (i.e. why does it show the last one but not the ones before?)
The code with the plotting parts are below. I've removed some parts because they seem unnecessary (but can add them if they are indeed relevant).
HHIplot = ggplot(pergame)
# some ggplot geoms and misc. here
ggsave(paste("HHI Index of all games,",year,"Finals.png"),
path = plotpath, width = 6, height = 4)
HHIAvePlot = ggplot(AveHHI, aes(x = AveHHI$n_brokers))
# some ggplot geoms and misc. here
ggsave(paste("Average HHI Index of all games,",year,"Finals.png"),
path = plotpath, width = 6, height = 4)
I've already taken a look here and here but neither have helped. Adding a print(HHIplot) or print(HHIAvePlot) after the ggsave() lines has not displayed the plot.
Many thanks in advance.
Update 1: The solution suggested below didn't work, although it works for the answer's sample code. I passed the ggplot objects to .Globalenv and print() gives me an empty gray box on the plot area (which I imagine is an empty ggplot object with no layers). I think the issue might lie in some of the layers or manipulators I have used, so I've brought the full code for one ggplot object below. Any thoughts? (Note: I've tried putting the assign() line in all possible locations in relation to ggsave() and ggplot().)
HHIplot = ggplot(pergame)
HHIplot +
geom_point(aes(x = pergame$n_brokers, y = pergame$HHI)) +
scale_y_continuous(limits = c(0,10000)) +
scale_x_discrete(breaks = gameSizes) +
labs(title = paste("HHI Index of all games,",year,"Finals"),
x = "Game Size", y = "Herfindahl-Hirschman Index") +
theme(text = element_text(size=15),axis.text.x = element_text(angle = 0, hjust = 1))
assign("HHIplot",HHIplot, envir = .GlobalEnv)
ggsave(paste("HHI Index of all games,",year,"Finals.png"),
path = plotpath, width = 6, height = 4)
I'll preface this by saying that the following is bad practice. It's considered bad practice to break a programming language's scoping rules for something as trivial as this, but here's how it's done anyway.
So within the body of your function you'll create both plots and put them into variables. Then you'll use ggsave() to write them out. Finally, you'll use assign() to push the variables to the global scope.
library(ggplot2)
myFun <- function() {
#some sample data that you should be passing into the function via arguments
df <- data.frame(x=1:10, y1=1:10, y2=10:1)
p1 <- ggplot(df, aes(x=x, y=y1))+geom_point()
p2 <- ggplot(df, aes(x=x, y=y2))+geom_point()
ggsave('p1.jpg', p1)
ggsave('p2.jpg', p2)
assign('p1', p1, envir=.GlobalEnv)
assign('p2', p2, envir=.GlobalEnv)
return()
}
Now, when you run myFun() it will write out your two plots to .jpg files, and also drop the plots into your global environment so that you can just run p1 or p2 on the console and they'll appear in RStudio's Plot pane.
ONCE AGAIN, THIS IS BAD PRACTICE
Good practice would be to not worry about the fact that they're not popping up in RStudio. They wrote out to files, and you know they did, so go look at them there.

Text not appearing on XTS plot

I'm having trouble adding some text to an plot of time series data in R using xts. I've produced a simple example of the problem.
My text() command seems to do nothing, whereas I can add a points to the plot. I've tried to keep the code simple by using defaults where possible
require(quantmod)
# fetch the data and plot it using default options
getSymbols('MKS.L')
plot(MKS.L$MKS.L.Close)
# try to add text - doesn't appear
text(as.Date('2012-01-01'),y=500,"wobble", cex=4)
# add a point - this does appear
testPos <- xts(600, as.Date('2012-01-01'))
points( testPos, pch = 3, cex = 4, col = "red" )
Any help appreciated - I'm pretty new to R and I've spent hours on this!
Not a direct answer, but the plot.xts function that comes with the xts package is not fully developed.
You're much better off using plot.zoo or plot.xts from the xtsExtra package (which was written as a Google Summer of Code project with the intention being to roll it into the xts package)
Either of these will work:
plot(as.zoo(MKS.L$MKS.L.Close))
text(as.Date('2012-01-01'),y=500,"wobble", cex=4)
#install.packages("xtsExtra", repos="http://r-forge.r-project.org")
xtsExtra::plot.xts(MKS.L$MKS.L.Close)
text(as.Date('2012-01-01'),y=500,"wobble", cex=4)

qplot dynamic plotting

I would like to create dynamic plotting over given dates, ie i want the plots appear one after another through specific dates when the code is run. This code seems to work with plot function but not with qplot.
any ideas?
thanks in advance,
x with headings t, date, AUM, profit
windows(5,5)
dev.set()
for (i in 1:10){
z <- x[x$t == i,]
a <- unique(z$date)
qplot(z$AUM,z$profit,main=a,xlim=range(0:2.5e+08),ylim=range(0:6e+06))
}
You need to add a print() call, i.e. print(qplot(...)).
The reason is that ggplot2 uses grid graphics which requires a print call.
print(qplot(z$AUM,z$profit,main=a,xlim=range(0:2.5e+08),ylim=range(0:6e+06)))
This is R FAQ 7.16.

Resources