Saving a plot in 'R' in 'eps' or 'pdf' format via 'rgl.postscript' (why color is changed?) - r

I am trying to run this code in "R" in order to plot a density function kernel smoothing and then save the plot as an "eps" file:
library(ks)
library(rgl)
kern <- read.table(file.choose(), sep=",")
hat <- kde(kern)
plot(hat, drawpoints=TRUE, xlab = "x", ylab= "y", zlab= "z")
rgl.postscript("plot1.eps","eps",drawText=TRUE)
The problem is that when I save the plot in eps format, it just shows the plot in one color (yellow) instead of a rage of colors (yellow, orange, red...) which shows different densities... (The plot in R is fine but when I save it as eps, the color is changed)
Do you know what is the problem with this code, or could you introduce me any other function that can save the plot that I generated in R as pdf or eps? (since it's an interactive RGL plot, I cannot use pdf() function. Also I tried rgl.snapshot, but every time it crashes and seems doesn't work...Following is part of my data: (x,y,z locations of points)
163.911642 248.952593 1.428709101
163.930843 249.077891 0.425459167
163.773321 249.288606 2.319076487
162.256416 246.990378 2.658388572
165.300014 247.950225 2.151660061
164.922344 249.017609 0.848590512
163.909127 248.881616 2.466267052
163.91322 249.118025 0.576787314
164.658937 249.547614 1.25279399
378.710211 132.601628 0.109772592
379.402818 132.858292 0.756297975
379.91023 132.912093 0.436653026
379.453418 132.815987 0.349591828
379.46519 132.694182 0.648543879
378.01787 132.615919 0.245000332
56.816299 27.469173 2.587220473
56.958051 27.103275 3.64182119
55.763676 26.59811 2.957732481
55.299606 26.054619 0.924209356
56.505342 27.671528 4.191381437
... ... ...
295.366938 24.360195 2.779443783
291.361501 23.21226 0.975021774
292.26276 22.053726 1.092983265
159.333055 41.087969 0.185656788
154.424175 37.83109 3.327367998
158.723404 40.487105 0.563578901
157.204282 41.678425 1.464830439

What I understand from your question is that the colours become different from what is displayed in X11 (assuming Linux environment) and the postscript (or eps) file.
Gnuplot colours are set for different terminal i.e. colours admissible to different terminals. So, the colours displayed in X11 (the default display term in Linux or Mac OSX) may be different in postscript.
To examine the permissible colours in a particular terminal is the Gnuplot command test. So, inside Gnuplot, the following set of command will produce a test.eps which when displayed will give you an idea what real colours you will be reproducing.
gnuplot> set term post colour eps
gnuplot> se out 'test.eps'
gnuplot> test
gnuplot> se te X11
Look at the test.eps file for true colour reproduction.

Related

RStudio y-axis label displays incomplete letters

When I use base R to plot something, then certain characters will not be displayed correctly, e.g.
plot(1:10,1:10, xlab = paste(letters[1:26], collapse =''), ylab = paste(letters[1:26], collapse =''))
produces the following plot:
Characters such as h, n and u are chopped off in the console view - however only on the y-axis. Exporting the plot via png() does not work, either. I have noticed that this problem only occurs when the code is executed in RStudio (Version 2022.07.0 Build 548, Windows 10).

Creating animated plots in the command line with Julia

Julia has the delightful ability to generate plots constructed from Unicode symbols which are printed directly to the command line in a very straightforward way. For example, the following code generates a Unicode plot of a sine function directly to the command line:
using Plots
unicodeplots();
x = [0:0.1:2*pi;];
y = sin.(x);
plot(x,y)
I would like to try to find a way to create an animated plot of this form directly on the command line. Ideally, I would like to generate a single plot in Unicode that is ``updated" in such a way that it appears animated.
However, although printing hundreds of distinct frames to the command line is naturally less appealing, such a solution is acceptable if it ``looks" like an animation. Another less acceptable solution is to print such Unicode plots into a gif in a way that is consistent for all platforms; attempts to do any of this involving jury-rigging #animate and #gif have largely failed, since either function cannot even print Unicode plots to a file in the Windows form of Julia.
UPDATE: Here is an example of code that generates an "animation" in the command line that is not really acceptable, which simply plots each distinct frame followed by "spacing" in the command line provided by a special Unicode character (tip provided by niczky12):
using Plots
unicodeplots();
n = 100;
x = [0:0.1:4*pi;];
for i = 1:30
y = sin.(x .+ (i/2));
plot(x, y, show=true, xlims = (0,4*pi), ylims = (-1,1))
sleep(0.01)
println("\33[2J")
end
A slight improvement might be this:
let
print("\33[2J")
for i in 1:30
println("\33[H")
y = sin.(x .+ (i/2));
plot(x, y, show=true, xlims = (0,4*pi), ylims = (-1,1))
sleep(0.01)
end
end

Rendering graphics in R Markdown

I have been using R Markdown to reproduce R code and report on some data processing. In terms of plotting, there is a difference between what is output to the RStudio IDE and what is rendered via knitr in html. The follwing is the code that applies to both situations
barplot(top10summariseDamage$totalDamage,
names.arg = c('Hurricane Opal','Heavy Rain/Severe Weather',
'Tornadoes, TSTM Wind, Hail', 'Severe Thunderstorm',
'Wild Fires', 'Hail Storm', 'Major Flood',
'Hurricane Opal/High Winds', 'Winter Storm/High Winds',
'Record Cold'),
ylim = c(0, 5*10^10), las = 2, ylab = 'Dollars Damage ($)',
main = "Economic Damage by Event Type")
The following is a dput of the vector being plotted, where I have added commas to the number for additional clarity
c(31728479000, 2.5e+10, 16000002500, 12053600200, 6.241e+09,
2.41e+09, 1.05e+09, 1000010000, 600005000, 5.6e+08)
Which in RStudio correctly produces the following
As you can see the left most bar is less than 4e10. However, when I use knitr to produce an html report, the following is rendered
As you can see the bar values are literally off the scale, even though I increased the y axis by a factor of 10. Any help appreciated.

plot got cut off after saving to file

My fig has a large legend outside the plot. 6 lines with long description When I save it, the legend doesn't show up. I adjusted par, but it still doesn't work.
legend("topright", inset=c(-0.6,0),xpd=TRUE,cex=0.8,
+legend=c("A_all peaks","B_ from all peaks","C_from all peaks","A_from unique peaks",
+"B_from unique peaks","C_from unique peaks",
+"A_from overlap peaks","B_from overlap peaks","C_from overlap peaks"),
+col=c("green","red","blue","lightgreen","pink","lightblue","darkgreen","darkred","steelblue"),
+pch=c(20,20,20,20,20,20,20,20,20),bty="n")
> par()$oma
[1] 2 2 2 2
> par()$mar
[1] 5.1 4.1 4.1 8.0
When save it with long width(tried 800,1000 pixel), no legend showed. But when as as short width(), part of legend shows. This is really confused me.first graph is 500*333, second graph is 500*800.
Not sure how you're saving the plot to file, but my usual routine is to make a pretty plot in R by the usual means:
plot(blah,blah,blah)
legend(blah,blah,blah)
and then once I'm happy with the appearance of the figure the R console, I use pdf() or one of it's cousins(jpeg(),tiff(), etc.) to save it to file, making sure to set the width and height parameters like so:
# set up plotting device
pdf( {{FileName}},
width = par('din')[1],
height = par('din')[2])
plot(blah,blah,blah)
legend(blah,blah,blah)
# disconnect the plotting device
dev.off()
Save it using png() or tiff():
tiff("filename",
<code for plot>,
height=5,width=7)
dev.off()
After plotting, try
% your codeā€¦
dev.copy(pdf, 'yourfile.pdf')
dev.off()
From https://statistics.berkeley.edu/computing/saving-plots-r

Clearing plotted points in R

I am trying to use the animation package to generate an "evolving" plot of points on a map. The map is generated from shapefiles (from the readShapeSpatial/readShapeLines functions).
The problem is when it's plotted in a for loop, the result is additive, whereas the ideal result is to have it evolve.
Are there ways of using par() that I am missing?
My question is: is there a way to clear just the points ploted from the points function
and not clearing the entire figure thus not having to regraph the shapefiles?
in case someone wants to see code:
# plotting underlying map
newyork <- readShapeSpatial('nycpolygon.shp')
routes <- readShapeLines('nyc.shp')
par(bg="grey25")
plot(newyork, lwd=2, col ="lightgray")
plot(routes,add=TRUE,lwd=0.1,col="lightslategrey")
# plotting points and save to GIF
ani.options(interval=.05)
saveGIF({
par(bg="grey25")
# Begin loop
for (i in 13:44){
infile <-paste("Week",i,".csv",sep='')
mydata <-read.csv(file = infile, header = TRUE, sep=",")
plotvar <- Var$Para
nclr <- 4
plotclr <-brewer.pal(nclr,"RdPu")
class<- classIntervals(plotvar,nclr,style = "pretty")
colcode <- findColours(class,plotclr)
points(Var$Lon,Var$Lat,col=colcode)
}
})
If you can accept a residual shadow or halo of ink, you can over-plot with color ="white" or == to your background choices. We cannot access your shape file but you can try it out by adding this line:
points(Var$Lon, Var$Lat, col="grey25")
It may leave gaps in other previously plotted figures or boundaries, because it's definitely not object-oriented. The lattice and ggplot2 graphics models are more object oriented, so if you want to post a reproducible example, that might be an alternate path to "moving" forward. I seem to remember that the rgl package has animation options in its repetoire.

Resources