Sharing contour plot attributes between subplots - plot

I'm plotting several contour plots side by side for visualizing the time evolution of certain function. I want each contour's value and color to be shared between all subplots, but each time I add a new subplot, the contour values are recomputed (as shown in the image below), so any comparison between them is meaningless.
Contour plots with colorbars http://www.inf.utfsm.cl/~rbonvall/colorbar-and-contour-plots.png
I've tried setting manually different combinations of cmap, colorbar and axes attributes on each subplot instance, without success. How can I share the contour plot attributes between all the subplots? In other words, how to get the same colorbar for all subplots?

You can directly specify the contour values to be used in the contour plot. Here's an example:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-1.2, 1.2, .025)
y = np.arange(-1.2, 1.2, .025)
X, Y = np.meshgrid(x, y)
Z = np.cos(X)*np.cos(Y)
Z = Z*Z
plt.subplot(1,2,1)
CS = plt.contour(X, Y, Z) # set levels automatically
plt.clabel(CS, inline=1, fontsize=10)
plt.subplot(1,2,2)
CS = plt.contour(X, Y, Z-.1, CS.levels) # set levels as previous levels
plt.clabel(CS, inline=1, fontsize=10)
plt.show()

Related

How to make custom spacing for y-axis in R?

I want to make a plot in R where the spacing between ticks on the y-axis all have the same distance and the tick labels are a custom list of values, for example:
set.seed(1)
n <- 10
x <- 1:n
y <- rnorm(n)
plot(x, y, axes = FALSE, ylim=c(-2,2))
axis(1)
axis(2, seq(-2,2,1), c(-100,-10,0,5,1000))
gets me a plot where the distance between the y-axis ticks are equal but clearly the true distance between values is not equal, i.e., -100 to - 10 is not the same distance as 5 to 1000, numerically.
Now this works, but the problem with this solution is that the data is not correctly mapped to the right position in the plot. As in, I would like for the data to be plotted correctly based on the original scale. So either I need a way to simply change the y-axis to be plotted on a different scale, or for the data to be transformed to a new scale that matches my axis(2, seq(-2,2,1), c(-100,-10,0,5,1000)) command.
I guess what I am saying is I want the equivalent of plot(x, y, log = "y") but I don't actually want the log scale, I just want the tick marks to be even spaced based on values I want shown, i.e., -100,-10,0,5,1000
Your example is a bit hard to implement because you are setting the plot boundaries from -2 to 2 and then wanting axis labels that go from -100 to 1000. It should work if you use at and set the boundaries of the initial plot to match the axis parameters. I've modified your example to spread the data across the plot more evenly:
set.seed(1)
n <- 10
x <- 1:n
y <- 100*rnorm(n)
yticks = c(-100,-10,0,5,200)
plot(x, y, axes = FALSE, ylim=c(-100,200))
axis(1)
axis(2,at = yticks,labels=yticks)

How to remove colour scale legend from plot() of spp density in R

I am plotting the density of a two-dimensional, weighted spatial point pattern. I'd like to make the plot without a colour scale legend, and save it with no (or minimal) boarders on all sides, like this: My problem is that I can't remove the colour scale legend. Reproducible code below:
## Install libraries:
library(spatstat) #spatial package
library(RColorBrewer) #create custom colour ramps
## Create reproducible data:
data <- data.frame(matrix(ncol = 3, nrow = 50))
x <- c("x", "y", "weight")
colnames(data) <- x
data$x <- runif(50, 0, 20)
data$y <- runif(50, 0, 20)
data$weight <- sample(1:200, 50)
## Set plotting window and colours:
plot.win <- owin(c(0,20), c(0,20)) # plot window as 20x20m
spat.bat.frame <- NULL # create a frame to store values in
cols1<-colorRampPalette(brewer.pal(9,"Blues"))(100) #define colour ramp for density plots
## Create and save plots:
jpeg(filename = "Bad plot.jpeg", res = 300, units = "cm", width = 20, height = 20)
par(mar=c(0,0,0,0),oma=c(0,0,0,0),lwd=1)
ppp_01 <- ppp(x = data$x, y = data$y, window = plot.win)
ppp_02 <- ppp(x = data$x, y = data$y, window = plot.win)
plot(density(ppp_01, weights = data$weights), main=NULL, col=cols1, sigma = 1)
plot(ppp_02, add=TRUE) #add spp points to density plot
dev.off()
I've tried legend=FALSE, auto.key=FALSE, colorkey=FALSE, which don't seem to be compatible with plot() (i.e. they don't give an error but don't change anything). I've also tried some work-arounds like saving a cropped image with dev.off.crop() or by adjusting margins with par(), but haven't been able to completely remove the legend. Does anyone have any suggestions on how to remove a colour scale legend of a density spp (real-valued pixel image) using plot()?
I specifically need to plot the density of the spatial point pattern, to specify a custom colour ramp, and to overlay the spp points onto the density image. I could try plotting with spplot() instead, but I'm not sure this will allow for these three things, and I feel like I'm missing a simple fix with plot(). I can't crop the figures manually after saving from R because there are 800 of them, and I need them all to be exactly the same size and in the exact same position.
Thank you!
Since plot is a generic function, the options available for controlling the plot will depend on the class of object that is being plotted. You want to plot the result of density(ppp_01, weights = data$weights). Let's call this Z:
Z <- density(ppp_01, weights = data$weights, sigma=1)
Note: the smoothing bandwidth sigma should be given inside the call to density
To find out about Z, you can just print it, or type class(Z).
The result is that Z is an object of class"im" (pixel image).
So you need to look up the help file for plot.im, the plot method for class "im". Typing ?plot.im shows that there is an argument ribbon that controls whether or not the colour ribbon is displayed. Simply set ribbon=FALSE in the call to plot:
plot(Z, ribbon=FALSE, main="", col=cols1)
Or in your original code
plot(density(ppp_01, weights=data$weights, sigma=1), main="", col=cols1)
However I strongly recommend separating this into two lines, one which creates the image object, and one which plots the image. This makes it much easier to spot mistakes like the misplacement of the sigma argument.

R how to automatically adjust y axis when using basic plot with xlim

I'm trying to use base R (and would like to stick to it for this problem) to plot a specific portion of a dataset.
My example data looks like below:
x <- c(1:100)
y <- sort(runif(100, min=0, max=1000))
When I plot this with plot(x,y, type='l'), I get a plot with a y axis that shows 0 to 1000. However, when I plot only a specific x range, my y axis still shows 0 to 1000. I would like to zoom in to reduce the y axis range.
For example,
plot(x,y, type='l', xlim=c(40,60))
plot(x,y, type='l', xlim=c(80,90))
both produces plots with a y axis that ranges c(0,1000). But I'd like to zoom in so that the y axis range for the first plot is something like c(300,700) and that for the second plot is c(700,1000). (300, 700 and 1000 are all arbitrary numbers just to illustrate the purpose to really zoom into the plot). Is there a way to do this without setting specific ylim?
I'd like to avoid using ylim because I'm plotting and saving in a for loop and I can't write a ylim that is suitable for all plots. I've thought of doing something like ylim = max(y)*1.5, but again, since I'm cutting the y values off based on xlim, this doesn't help with zooming in whenever xlim changes.
Subset the relevant data and plot that
lower = 40
upper = 60
ind = which(x >= lower & x <= upper)
plot(x[ind], y[ind], type = "l")

label axis with different distance from the plot

Is there any way to set different distances between the label axes and the plot? I know I can set the distance of label axes to the plot with the par(mgp=c()) command, but I need to set different distances for x and y labels.
Thanks
If you are looking to change the distance between the plot and the labels then you can use:
par(mar = c(w,x,y,z) + a)
Where altering the values of w, x, y, z and a will alter the spacing between your plot and your axes. A helpful tutorial can be found here:
http://www.r-bloggers.com/setting-graph-margins-in-r-using-the-par-function-and-lots-of-cow-milk/

Labels/points colored by category with PCA

I'm using prcomp to do PCA analysis in R, I want to plot my PC1 vs PC2 with different color text labels for each of the two categories,
I do the plot with:
plot(pca$x, main = "PC1 Vs PC2", xlim=c(-120,+120), ylim = c(-70,50))
then to draw in all the text with the different colors I've tried:
text(pca$x[,1][1:18], pca$[,1][1:18], labels=rownames(cava), col="green",
adj=c(0.3,-0.5))
text(pca$x[,1][19:35], pca$[,1][19:35], labels=rownames(cava), col="red",
adj=c(0.3,-0.5))
But R seams to plot 2 numbers over each other instead of one, the pcs$x[,1][1:18] plots the correct points I know because if I use that plot the points it works and produces the same plot as plot(pca$x).
It would be great if any could help to plot the labels for the two categories or
even plot the points different color to make it easy to differentiate between the plots easily.
You need to specify your x and y coordinates a bit differently:
text(pca$x[1:18,1], pca$x[1:18,2] ...)
This means take the first 18 rows and the first column (which is PC1) for the x coord, etc.
I'm surprised what you did doesn't throw an error.
If you want the points themselves colored, you can do it this way:
plot(pca$x, main = "PC1 Vs PC2", col = c(rep("green", 18), rep("red", 18)))

Resources