How to plot polar coordinates in R? - r

Suppose that (x(t),y(t)) has polar coordinates(√t,2πt). Plot (x(t),y(t)) for t∈[0,10].
There is no proper function in R to plot with polar coordinates. I tried normal plot by giving, x=√t & y=2πt.
But resultant graph was not as expected.
I got this question from "Introduction to Scientific Programming  and Simulation using r"and the book is telling the plot should be spiral.

Make a sequence:
t <- seq(0,10, len=100) # the parametric index
# Then convert ( sqrt(t), 2*pi*t ) to rectilinear coordinates
x = sqrt(t)* cos(2*pi*t)
y = sqrt(t)* sin(2*pi*t)
png("plot1.png");plot(x,y);dev.off()
That doesn't display the sequential character, so add lines to connect adjacent points in the sequence:
png("plot2.png");plot(x,y, type="b");dev.off()

As already mentioned in a previous comment, R can plot using polar coordinates. The package plotrix has a function called polar.plot that does this. Polar coordinates are defined by length and angle. This function can take a sequence of lengths and a sequence of angles to plot with polar coordinates. For example to make one spiral:
library(plotrix)
plt.lns <- seq(1, 100, length=500)
angles <- seq(0, 5*360, length=500)%%360
polar.plot(plt.lns, polar.pos=angles, labels="", rp.type = "polygon")

An option worth a try, It is Plotly package.
library(plotly)
p <- plot_ly(plotly::mic, r = ~r, t = ~t, color = ~nms, alpha = 0.5, type = "scatter")
layout(p, title = "Mic Patterns", orientation = -90)
Note: If you are using RStudio, the plots are going to be shown in Viewer tab.

Related

Visualize 3D data in Julia

I know the function:
surf(lst1,lst2,lst3)
Is there another one that does the same thing but in the 2d graph, similar to the heat map?
Plotting lst1, lst2 with zcolor = lst3 using a large marker or a scatter plot would do that.
using Plots
x = 0.0:π/20:2π
y = sin.(x)
z = tanh.(x)
plot(x, y, marker = 10, zcolor = z)
I’m not clear on the type of graph that you want. The closest thing I can think of for a surface plot in 2D would be a contour plot. The Plots interface has a contour() function, which you can call the same way as the heatmap() function (but has, of course, its own special keywords).

Plotting a 3D surface from x, y, z scatter data in R

I have a dataframe of coordinates (x,y,z) where a function takes value 1, with all other coordinates being set to 0. Here is a simplified sample dataset analogous to what I am working with:
dd <- data.frame(x = c(rep(1,9),rep(2,9),rep(3,9)),
y=rep(c(rep(1,3),rep(2,3),rep(3,3)),3),
z= rep(c(1,2,3),3^2),
t = rep(1,3^3))
As can be seen from the following scatter plot, these points define a cube:
plot_ly(df, x = ~dd$x, y=~dd$y,z=~dd$z,
type = 'scatter3d',
mode = 'markers')
I would like to plot the surfaces enclosing this cube but I can't figure out how to do it (note that in my data the shape is more complex and there is no explicit function defining z as a function of x and y but still define a polyhedron). I tried using plot_ly with various options, surface3d (including solution given at R: Plotting a 3D surface from x, y, z, and many other options suggested at StackOverflow but I can't get the full cube plotted. Any suggestion will be greatly appreciated.

Access lines plotted by R using basic plot()

I am trying to do the following:
plot a time series in R using a polygonal line
plot one or more horizontal lines superimposed
find the intersections of said line with the orizontal ones
I got this far:
set.seed(34398)
c1 <- as.ts(rbeta(25, 33, 12))
p <- plot(c1, type = 'l')
# set thresholds
thresholds <- c(0.7, 0.77)
I can find no way to access the segment line object plotted by R. I really really really would like to do this with base graphics, while realizing that probably there's a ggplot2 concoction out there that would work. Any idea?
abline(h=thresholds, lwd=1, lty=3, col="dark grey")
I will just do one threshold. You can loop through the list to get all of them.
First find the points, x, so that the curve crosses the threshold between x and x+1
shift = (c1 - 0.7)
Lower = which(shift[-1]*shift[-length(shift)] < 0)
Find the actual points of crossing, by finding the roots of Series - 0.7 and plot
shiftedF = approxfun(1:length(c1), c1-0.7)
Intersections = sapply(Lower, function(x) { uniroot(shiftedF, x:(x+1))$root })
points(Intersections, rep(0.7, length(Intersections)), pch=16, col="red")

Formatting and manipulating a plot from the R package "hexbin"

I generate a plot using the package hexbin:
# install.packages("hexbin", dependencies=T)
library(hexbin)
set.seed(1234)
x <- rnorm(1e6)
y <- rnorm(1e6)
hbin <- hexbin(
x = x
, y = y
, xbin = 50
, xlab = expression(alpha)
, ylab = expression(beta)
)
## Using plot method for hexbin objects:
plot(hbin, style = "nested.lattice")
abline(h=0)
This seems to generate an S4 object (hbin), which I then plot using plot.
Now I'd like to add a horizontal line to that plot using abline, but unfortunately this gives the error:
plot.new has not yet been called
I have also no idea, how I can manipulate e.g. the position of the axis labels (alpha and beta are within the numbers), change the position of the legend, etc.
I'm familiar with OOP, but so far I could not find out how plot() handles the object (does it call certain methods of the object?) and how I can manipulate the resulting plot.
Why can't I simply draw a line onto the plot?
How can I manipulate axis labels?
Use lattice version of hex bin - hexbinplot(). With panel you can add your line, and with style you can choose different ways of visualizing hexagons. Check help for hexbinplot for more.
library(hexbin)
library(lattice)
x <- rnorm(1e6)
y <- rnorm(1e6)
hexbinplot(x ~ y, aspect = 1, bins=50,
xlab = expression(alpha), ylab = expression(beta),
style = "nested.centroids",
panel = function(...) {
panel.hexbinplot(...)
panel.abline(h=0)
})
hexbin uses grid graphics, not base. There is a similar function, grid.abline, which can draw lines on plots by specifying a slope and intercept, but the co-ordinate system used is confusing:
grid.abline(325,0)
gets approximately what you want, but the intercept here was found by eye.
You will have more luck using ggplot2:
library(ggplot2)
ggplot(data,aes(x=alpha,y=beta)) + geom_hex(bins=10) + geom_hline(yintercept=0.5)
I had a lot of trouble finding a lot of basic plot adjustments (axis ranges, labels, etc.) with the hexbin library but I figured out how to export the points into any other plotting function:
hxb<-hexbin(x=c(-15,-15,75,75),
y=c(-15,-15,75,75),
xbins=12)
hxb#xcm #gives the x co-ordinates of each hex tile
hxb#ycm #gives the y co-ordinates of each hex tile
hxb#count #gives the cell size for each hex tile
points(x=hxb#xcm, y=hxb#ycm, pch=hxb#count)
You can just feed these three vectors into any plotting tool you normally use.. there is the usual tweaking of size scaling, etc. but it's far better than the stubborn hexplot function. The problem I found with the ggplot2 stat_binhex is that I couldn't get the hexes to be different sizes... just different colors.
if you really want hexagons, plotrix has a hexagon drawing function that i think is fine.

3d plot in R - Patch

I have the following data in a data frame:
**x** in (0,1)
**y** in [0,1]
**z** in [0,1]
For example:
X,Y,Z
0.1, 0.2, 0.56
0.1, 0.3, 0.57
...
I'd like to plot them on this type of chart:
I tried on R, but all I could get was a not-so-fancy 3d scatterplot.
I also read about the lattice 3d wireframe, but I couldn't get my head around it.
What am I supposed to do to get a Matlab like wireframe in R?
What data transforms are involved?
This is the sample code from the documentation:
x <- seq(-pi, pi, len = 20)
y <- seq(-pi, pi, len = 20)
g <- expand.grid(x = x, y = y)
g$z <- sin(sqrt(g$x^2 + g$y^2))
wireframe(z ~ x * y, g, drape = TRUE,
aspect = c(3,1), colorkey = TRUE)
I don't find it particularly clear.
EDIT: the persp3d function works fine, and I was able to generate a 3d plot with one colour. How can I set a colour scale relative to the z value?
Thanks for any hints,
Mulone
Use outer to create the z values and then use persp to plot:
z <- outer(x,y, function(x,y) sin(sqrt(x^2+y^2)))
persp(x,y,z)
There are options for colouring and setting the viewing angle, see ?persp. See the fourth example for Matlab style colouring.
For an interactive plot, consider using persp3d in the rgl package:
require(rgl)
persp3d(x,y,z,col="blue")
Edit
To add colour, there is a slight difference from the method in persp, since the colour relates to the vertex rather than the centre of the facet, but it makes it easier.
jet.colors <- colorRampPalette( c("blue", "green") )
pal <- jet.colors(100)
col.ind <- cut(z,100) # colour indices of each point
persp3d(x,y,z,col=pal[col.ind])
The help file recommends adding the parameter smooth=FALSE, but that's down to personal preference.

Resources