I'm having trouble getting 'choice' to create output. When the graphical interface launches, I am selecting a partition with the space bar. This creates a black circle around the partition, indicating it has been selected. When I click 'return', nothing happens.
I checked my working directory to look for the output files, but they are not there. I used getwd() to ensure that I have the correct setwd(). No dice.
There was a similar question posted: Exporting result from kml package in R; however, the answer does not work for me.
Any suggestions? I am using R 3.1.0 GUI Mavericks build(6734) and XQuartz 2.7.6. Thanks for any help getting this working.
Here is my code:
setwd("/Users/eightfrench")
mydata <- read.csv("hcris_long3.csv")
cldHCRIS <- clusterLongData(traj=mydata)
kml(cldHCRIS,nbClusters=2:4,nbRedrawing=2,toPlot="both")
X11(type="Xlib")
choice(cldHCRIS, typeGraph= "bmp")
I had the same problem when using RStudio and i solved it just opening the x11 device with no specification. Like this:
setwd("/Users/eightfrench")
mydata <- read.csv("hcris_long3.csv")
cldHCRIS <- clusterLongData(traj=mydata)
kml(cldHCRIS,nbClusters=2:4,nbRedrawing=2,toPlot="both")
X11()
choice(cldHCRIS, typeGraph= "bmp")
Hope this also works for you.
The new version of kml (2.3) fix that, it provide a key to export data with linux as well (not "return" since getGraphicsEvent does not accept "return" using linux, so I have to map another key : 'm')
Christophe
Related
I'm unable to save a plot generated by the plot.Node function in data.tree. I've tried the following:
### Create tree object and plot it
data(acme);
plot(acme);
This works fine, showing the plot, as one would expect.
### Try saving it as png
png(filename='file.png', type='cairo-png');
plot(acme);
dev.off();
This creates an empty file. ggsave does the same. Apparantly, plot.Node uses DiagrammeR under the hood, so I looked into that package. It has a function to export graphs:
export_graph(acme, file_name="file.png");
This gives the error:
Error in file.exists(diagram) : invalid 'file' argument
When I transform to GraphViz first, I get a different error:
export_graph(ToGraphViz(acme), file_name="file.png");
Error in graph$dot_code : $ operator is invalid for atomic vectors
Clearly, exporting to GraphViz doesn't quite export to what DiagrammeR expects.
I'm in RStudio and so could in theory just save the plot using the GUI, but I need this for in a script.
Apparently, plot.Node doesn't actually plot anything - instead it seems to generate html/js. Does this mean that that result cannot be stored as a graphic? Or is there some export/conversion function somewhere that I'm completely missing? it certainly feels like I'm missing something obvious - I assume the need to store plotted data.trees as images is quite common. But I have no idea which potential solutions I can still explore.
I'd be very grateful for any pointers anybody has!
As sebastian-c suggested, things work now a bit differently than suggested by Matherion, as of R 3.3.3 with data.tree 0.7.0 and DiagrammeR 0.9.0
Pre-requisite: DiagrmmeRsvg and dependencies need to be installed. Depending on your OS, for this to work you might have to install V8. For example on ubuntu:
apt-get install libv8-3.14-delibv8-3.14-dev
And then in R:
install.packages("DiagrammeRsvg")
On Windows, I didn't have to install anything (maybe because Chrome is installed?).
Once DiagrammeRsvg is available, run:
library(data.tree)
data(acme)
library(DiagrammeR)
export_graph(ToDiagrammeRGraph(acme), "export.pdf")
I've found the answer, at least, partially. There exists a package dedicated to exporting GraphViz diagrams to SVG: DiagrammeRsvg.
So this works:
treeAsSVG <- export_svg(grViz(ToGraphViz(acme)));
writeLines(treeAsSVG, "filename.svg"));
The grViz is necessary to actually convert the ToGRaphViz output to something that can be interpreted by export_svg. I'm still not really sure (yet) what all goes on under the hood - for example, this does not work:
export_graph(grViz(ToGraphViz(acme)), file_name="filename.svg");
But, if anybody else has a similar problem and stumbles upon this question, perhaps this partial answer can help them to at least export something that can then be integrated in e.g. html pages.
By converting acme with as.phylo() it works, but it looks a little boring:
plot(as.phylo(acme),
show.node.label=TRUE,
node.pos=2,
no.margin=TRUE
)
# adding edge labels
edgelabels(as.vector(acme$Get("cost"))[-1],
adj = c(0,-0.5),
frame = "none")
solution with as.phylo()
I also tried as.igraph. However, the nodes overlap and it looks even less pretty:
plot(0, type="n", ann=FALSE, axes=FALSE,
xlim=extendrange(ig[,1]),
ylim=extendrange(ig[,2]))
plot(ig,
layout=layout_as_tree(ig,root=1),
vertex.shape="rectangle",
vertex.size=(strwidth(V(ig)$name) + strwidth("oo")) * 100,
#vertex.size2=strheight("I") * 2 * 100,
edge.label=acme$Get("p",traversal = "level")[-1]
)
solution with as.igraph()
I am wondering if there is a function to clear the console in R and, in particular, RStudio I am looking for a function that I can type into the console, and not a keyboard shortcut.
Someone has already provided such a function in this StackExchange post from 2010. Unfortunately, this depends on the RCom package and will not run on Mac OS X.
cat("\014")
is the code to send CTRL+L to the console, and therefore will clear the screen.
Far better than just sending a whole lot of returns.
If you are using the default R console, the key combination Option + Command + L will clear the console.
You may define the following function
clc <- function() cat(rep("\n", 50))
which you can then call as clc().
shell("cls") if on Windows,
shell("clear") if on Linux or Mac.
(shell() passes a command (or any string) to the host terminal.)
cat("\f") may be easier to remember than cat("\014").
It works fine for me on Windows 10.
In Ubuntu-Gnome, simply pressing CTRL+L should clear the screen.
This also seems to also work well in Windows 10 and 7 and Mac OS X Sierra.
Here's a function:
clear <- function() cat(c("\033[2J","\033[0;0H"))
then you can simply call it, as you call any other R function, clear().
If you prefer to simply type clear (instead of having to type clear(), i.e. with the parentheses), then you can do
clear_fun <- function() cat(c("\033[2J","\033[0;0H"));
makeActiveBinding("clear", clear_fun, baseenv())
I developed an R package that will do this, borrowing from the suggestions above. The package is called called mise, as in "mise en place." You can install and run it using
install.packages("mise")
library(mise)
mise()
Note that mise() also deletes all variables and functions and closes all figures by default. To just clear the console, use mise(vars = FALSE, figs = FALSE).
In linux use system("clear") to clear the screen.
If you are using the default R console CTRL + L
RStudio - CTRL + L
cat("\014") . This will work. no worries
You can combine the following two commands
cat("\014");
cat(rep("\n", 50))
Another option for RStudio is rstudioapi::sendToConsole("\014"). This will work even if output is diverted.
sink("out.txt")
cat("\014") # Console not cleared
rstudioapi::sendToConsole("\014") # Console cleared
sink()
I know this question is very old, but I found myself visiting it many times looking for a totally different answer:
n = 20
for (i in 0:n) {
cat(100*i/n, "% \r")
flush.console()
Sys.sleep(0.01) #do something slow
}
flush.console() will kind of "clear the console in r and studio", maybe not in OP's terms but still.
This code will act like a progress bar in the console. For each iteration, the percentage is incremented and then erased on the next iteration.
Note that this won't work without \r or with an \n, for some reason.
When I want to create the map using the gvisGeoMap() from googleVis, I get error:
## Using the google visualization API with R
library(googleVis)
input<- read.csv("data.csv")
select<- input[which(input$Subgroup=="Total 5-14"),]
select<- input[which(input$Subgroup=="Total 5-14 yr"),]
Map<- data.frame(select$Country.or.Area, select$Value)
names(Map)<- c("Country", "Percentage")
Geo=gvisGeoMap(Map, locationvar="Country", numvar="Percentage",
options=list(height=350, dataMode='regions'))
plot(Geo)
#starting httpd help server ... done
#Error in ifelse(interactive(), getOption("browser"), "false") :
#replacement has length zero
The above is the error in the "RGui". The error message in "RStudio" is differet:
#object of type 'closure' is not subsettable
and the browser does not fire at all. The HTTP server works fine since I can simply call help pages.( for example ?googleVis will fire up the browser and give the help page). The "Geo" object in the code above is fine and contains the html code only that the plot() does not do what it is supposed to do (I can manually run the html file in the temp folder and see the results). The example above is available here.
I would appreciate your clues.
Thank you
This is the result of correspondance with the the Authors of the packages. It seems that there was a bug that prevented the plot to work properly. The released a new version. You can find the link below.
TQ
.....
Yesterday evening I realised that with version 0.3.0 of googleVis I unfortunately introduced a bug in RStudio and R on Windows.
The bug has been fixed already and a new version (0.3.1) is available from our project site (here is the link), but not on CRAN yet.
I have put a note on my blog (here is the link) to inform others as well.
I hope this helps.
Best regards
Markus
I'm trying to import a shape-file like this:
fn <- "Proj1"
my_shp <- readShapeSpatial(fn)
On a windows-computer (32-bit) it works ok, but when I do the same from a Ubuntu-machine (64-bit, English OS, R2.14.0), I get "Error in make.names(onames, unique = TRUE) : invalid multibyte string 9".
I suspect it is because the shapefile has Spanish origins, i.e. the names of polygons in it have accents like in "México" (not "Mexico").
As a quick fix, I did the import in windows, saved as .rda and loaded it in Ubuntu, but then I get for example "M\xfexico" as polygon name.
I'm not so experienced in Linux so I don't know if the fix is in R or in Ubuntu. Your help is highly appreciated.
The solution is to start R on the Ubuntu-computer by writing "LC_ALL=C R" in a terminal window. Thanks to Oscar Perpiñán for the solution.
Update: I use RStudio, where as far as I know it is not possible to start R with command-line parameters, but this works from inside RStudio:
Sys.setlocale(category = "LC_ALL", locale = "C")
/Chris
I am having an issue with the R package Rgooglemaps. I can retrieve a map from google maps or open street map but the PlotOnStaticMap function does not overlap the data I want to plot to the map. Instead it opens a new graphical device where it plots the data. So I end up with:
an image saved in my working dir which contains only the retrieved google map
a R graphic device window with my data plotted over a white background.
I am on windows, using R version 2.13.1 and RGUI. The issue appears also when I run the code via command line. I remember I used Rgooglemaps a few months ago and it worked properly for me. Meanwhile I upgraded my R version, so it could be a version related issue. Can someone give it a try and see if you have the same issue (and a way to solve it)? Here an example to reproduce the issue (taken from http://www.r-bloggers.com/visualizing-gis-data-with-r-and-open-street-map/). The example is using Open Street Map instead of googlemaps but the behavior is the same.
The code:
require(RgoogleMaps)
lat_c<-51.47393
lon_c<-7.22667
bb<-qbbox(lat = c(lat_c[1]+0.01, lat_c[1]-0.01), lon = c(lon_c[1]+0.03, lon_c[1]-0.03))
OSM.map<-GetMap.OSM(lonR=bb$lonR, latR=bb$latR, scale = 20000, destfile="bochum.png")
image(OSM.map)
lat<- c(51.47393, 51.479021)
lon<- c(7.22667, 7.222526)
val <- c(0, 255)
lat_adj<-function(lat, map){(map$BBOX$ll[1]-lat)/(map$BBOX$ll[1]-map$BBOX$ur[1])}
lon_adj<-function(lon, map){(map$BBOX$ll[2]-lon)/(map$BBOX$ll[2]-map$BBOX$ur[2])}
PlotOnStaticMap(OSM.map, lat = lat_adj(lat, OSM.map), lon = lon_adj(lon, OSM.map),
col=rgb(255,0, val,90,maxColorValue=255),pch=16,cex=4)
dev.print(jpeg,"test.jpeg", width=1204, height=644, units="px")
I've only re-run your code, and not looked into the problems and get the error message:
dev.print(jpeg,"test.jpeg", width=1204, height=644, units="px")
windows
2
Error: REAL() can only be applied to a 'numeric', not a 'NULL'
I ran the above code on R2.14.0 and everything appears to work.