I am trying to replicate these:
https://radacad.com/interactive-map-using-r-and-power-bi-create-custom-visual-part-1
Is it possible to use R Plotly library in R Script Visual of Power BI?
The issue with Plotly is that for my dataset it is so slow even when I am compiling that in R. takes several minutes. So, I have decided to replace it with googleVis which is really fast (I am open any other interactive Gantt Chart in R).
Here is my code in R:
df <- data.frame(Values)
library("googleVis")
#df$Project.Name <- toString(df$Project.Name)
df$Processed_start_date_cut <- as.Date(df$Processed_start_date_cut)
df$Processed_End_date <- as.Date(df$Processed_End_date)
#df$Milestone <- toString(df$Milestone)
g <- gvisTimeline(data=df,
rowlabel="Project.Name",
barlabel="Milestones",
start="Processed_start_date_cut",
end="Processed_End_date",
options=list(timeline="{rowLabelStyle:{fontName:'Helvetica',
fontSize:10, color:'#603913'},
barLabelStyle:{fontName:'Garamond',
fontSize:12}}",
backgroundColor='#ffd',
height=350 ))
cat(g$html$chart, file="out.html")
I have tried it in R and it works great. In BI this works for the first time, but when I change any filters, nothing shows up in this newly developed pbivis item unless I go to another tab of my report and then come back to this tab which has this newly developed pbivis (this was the reason I thought it is not working at first, sorry).
See the screenshot
I have also noticed that if I maximize this item (pbivis), then the chart disappears (i.e. shows nothing).
I guess I need a kind of code for refreshing the visuals which possibly can come before df <- data.frame(Values), maybe something like F5 in IE.
Also tried this and did not work:
if (file.exists("out.html"))
#Delete file if it exists
file.remove("out.html")
As user3867743 suggested, the issue is related to
cat(g$html$chart, file="out.html")
After replacing it by
print(g, file="out.html")
It has started working fine.
Related
Currently learning RStudio but for some reason my Console isn't outputting my code? Not sure if there was a setting I may have toggled but it seems to only affect me when I have a variable in my code?
For example:
when working the ToothGrowth dataset
data("ToothGrowth")
View(ToothGrowth)
This executes and I can view the table of the data in a separate tab.
However, when I try to filter it
data("ToothGrowth")
View(ToothGrowth)
filtered_tg = filter(ToothGrowth, dose=0.5)
View(filtered_tg)
Nothing Returns, a formatted table doesn't open and an empty line is returned in the console window.
This is just one example, even when i try something as simple as
number = 10
number
I would expect, in return;
[1] 10
But console is empty.
Looking for solutions online, I've seen maybe i didn't close a bracket or parenthesis and to include CloseAllConnections() if there was a '+' showing in the console (which there isn't).
Working on rstudio cloud so is there a reset somewhere that I could possibly try?
Thanks for any and all help!
I changed the function as follows:
filtered_tg = filter(ToothGrowth, dose=="0.5")
View(filtered_tg)
After running these commands it was viewed as the table of the data in a separate tab 👇
Output
Using dplyr in R (microsoft R Open 3.5.3 to be precise). I'm having a slight problem with dplyr whereby I'm sometimes seeing lots of additional information in the data frame I create. For example, for these lines of code:
claims_frame_2 <- left_join(claims_frame,
select(new_policy_frame, c(Lookup_Key_4, Exposure_Year, RowName)),
by = c("Accident_Year" = "Exposure_Year", "Lookup_Key_4" = "Lookup_Key_4")
)
claims_frame_3 <- claims_frame_2 %>% group_by(Claim.Number) %>% filter(RowName == max(RowName))
No problem with the left_join command, but when I do the second command (group by/filter), the data structure of the claims_frame_3 object is different to that of the claims_frame_2 object. Seems to suddenly have lots of attributes (something I know little about) attached to the RowName field. See the attached photo.
Does anyone know why this happens and how I can stop it?
I had hoped to put together a small chunk of reproducible code that demonstrated this happening, but so far I haven't been successful. I will continue. In the mean time, I'm hoping someone might see this code (from a real project) and immediately know why this is happening!
Grateful for any advice.
Thanks
Alan
I am doing java and R integration using JRI.
Please find below script
String path = "C:\\Users\\hrpatel\\Desktop\\CSVs\\DataNVOCT.csv";
rengine.eval("library(tseries)");
rengine.eval(String.format("mydata <- read.csv('%s')",path.replace('\\', '/')));
String exportFilePath= "C:\\Users\\hrpatel\\Desktop\\CSVs\\arima3.jpg";
rengine.eval("Y <- NewVisits");
rengine.eval("t <- Day.Index");
rengine.eval("summary(Y)");
rengine.eval("adf.test(Y, alternative='stationary')");
rengine.eval("adf.test(Y, alternative='stationary', k=0)");
rengine.eval("acf(Y)");
rengine.eval("pacf(Y)");
rengine.eval("mydata.arima101 <- arima(Y,order=c(1,0,1))");
rengine.eval("mydata.pred1 <- predict(mydata.arima101, n.ahead=1000)");
rengine.eval(String.format("jpeg('%s')",exportFilePath.replace('\\', '/')));
rengine.eval("plot(t,Y)");
rengine.eval("lines(mydata.pred1$pred, col='blue',size=10)");
rengine.eval("lines(mydata.pred1$pred+1*mydata.pred1$se, col='red')");
rengine.eval("lines(mydata.pred1$pred-1*mydata.pred1$se, col='red')");
rengine.eval("dev.off()");
In above codebase when i tried plot(t,Y) or plot(Y). it export a blank image, while in case of plot(mydata) it is working file.
One more thing when i run above code in R it creates the image(using JRI it shows blank image).
I have spend 1 day to solve this but i dont found any solution.
Please suggest if you have any alternatives.
Your help is needed.
Thanks in Advance
if i understand correctly, you have a data set named mydata, that has two columns, NewVisits, and Day.Index, in that case you need to change:
rengine.eval("Y <- NewVisits");
to
rengine.eval("Y <- mydata$NewVisits");
and
rengine.eval("t <- Day.Index");
to
rengine.eval("t <- mydata$Day.Index");
This also explains why plot(mydata) works for you - because R recognizes it.
if this isn't the solution, then i cant see where you are reading NewVisits and Day.Index from
BTW i stongly recommend to plot using the ggplot package
I do a lot of data exploration in R and I would like to keep every plot I generate (from the interactive R console). I am thinking of a directory where everything I plot is automatically saved as a time-stamped PDF. I also do not want this to interfere with the normal display of plots.
Is there something that I can add to my ~/.Rprofile that will do this?
The general idea is to write a script generating the plot in order to regenerate it. The ESS documentation (in a README) says it well under 'Philosophies for using ESS':
The source code is real. The objects are realizations of the
source code. Source for EVERY user modified object is placed in a
particular directory or directories, for later editing and
retrieval.
With any editor allows stepwise (or regionwise) execution of commands you can keep track of your work this way.
The best approach is to use a script file (or sweave or knitr file) so that you can just recreate all the graphs when you need them (into a pdf file or other).
But here is the start of an approach that does the basics of what you asked:
savegraphs <- local({i <- 1;
function(){
if(dev.cur()>1){
filename <- sprintf('graphs/SavedPlot%03d.pdf', i)
dev.copy2pdf( file=filename )
i <<- i + 1
}
}
})
setHook('before.plot.new', savegraphs )
setHook('before.grid.newpage', savegraphs )
Now just before you create a new graph the current one will be saved into the graphs folder of the current working folder (make sure that it exists). This means that if you add to a plot (lines, points, abline, etc.) then the annotations will be included. However you will need to run plot.new in order for the last plot to be saved (and if you close the current graphics device without running another plot.new then that last plot will not be saved).
This version will overwrite plots saved from a previous R session in the same working directory. It will also fail if you use something other than base or grid graphics (and maybe even with some complicated plots then). I would not be surprised if there are some extra plots on occasion that show up (when internally a plot is created to get some parameters, then immediatly replaced with the one of interest). There are probably other things that I have overlooked as well, but this might get you started.
you could write your own wrapper functions for your commonly used plot functions. This wrapper function would call both the on-screen display and a timestamped pdf version. You could source() this function in your ~/.Rprofile so that it's available every time you run R.
For latice's xyplot, using the windows device for the on-screen display:
library(lattice)
my.xyplot <- function(...){
dir.create(file.path("~","RPlots"))
my.chart <- xyplot(...)
trellis.device(device="windows",height = 8, width = 8)
print(my.chart)
trellis.device(device = "pdf",
file = file.path("~", "RPlots",
paste("xyplot",format(Sys.time(),"_%Y%m%d_%H-%M-%S"),
".pdf", sep = "")),
paper = "letter", width = 8, height = 8)
print(my.chart)
dev.off()
}
my.data <- data.frame(x=-100:100)
my.data$y <- my.data$x^2
my.xyplot(y~x,data=my.data)
As others have said, you should probably get in the habit of working from an R script, rather than working exclusively from the interactive terminal. If you save your scripts, everything is reproducible and modifiable in the future. Nonetheless, a "log of plots" is an interesting idea.
In the example below I would like to be able to control when I go to the next plot by a using mouse click (or keyboard entry)
for (i in 1:5){
plot(1:i)
Sys.sleep(1)
#add something here that requests mouse click to proceed
}
Is this possible? There is a setting in the X11() help file caled 'clickToConfirm' but I can't work out what that does.
It would also be helpful to me to be to be able to scroll back and forth through plots using the arrow keys. Is this possible?
Currently if I need to look at lots of plots I output them into a big .pdf file and scroll though them all there, but that is a bit cumbersome.
Thanks
Tom
In R, that would be done by setting par(ask=TRUE). Try the following code, which shows how to reset the par when exiting the function :
op <- par(ask=TRUE)
for (i in 1:5){
plot(1:i)
}
par(op)
If you want to keep a history to browse through, you can either open a window and click on recording in the History menu, or you can open the window yourself with the history on. Demonstrated in a function :
plot.fun <- function(){
windows(record=TRUE) # opens a window and starts recording
op <- par(ask=TRUE)
on.exit(par(op))
for (i in 1:5){
plot(1:i)
}
windows.options(record=FALSE) #stops recording.
}
plot.fun()
This will however keep all previous plots in the history for browsing as well, so if you run this code 3 times you'll have 15 plots in the plot history. Also note that the open plot window will keep on recording until you turn off the recording in the menu.
You can play with the plot history, as you'll have a variable .SavedPlots which contains the saved plot history. It can be cleared using the menu History > clear history in the plot window. If you want to clear the history from the console, you could hack that by
.SavedPlots <- NULL
But I advise you not to do this, as changing the .SavedPlots variable can cause R to crash.
See also ?windows and ?recordPlot for a bit more information. But as you're getting close to the internal code of R, be warned that you can get pretty awkward behaviour if you start playing around with these things.
For scrolling back and forth between plots using the arrow keys: it depends on the platform/R interface.
Windows: there is a recording function (see Q5 of the R for Windows FAQ) which uses Page Up/Page Down
MacOS: under the standard GUI, the Quartz window has Apple-left and Apple-right arrow
under the standard Unix (no-GUI) interface, things are more limited. You can use RStudio (which has a lot of buzz right now) ... I would have thought that JGR would have plot history as well, but it doesn't seem to ...
You can use locator - now plots change on click
for (i in 1:5){
plot(1:i)
locator(1)
}