My code
library(Hmisc)
r1 <- read.table("mt7.1r1.rp", header = FALSE)
r2 <- read.table("mt7.1r2.rp", header = FALSE)
r3 <- read.table("mt7.2r1.rp", header = FALSE)
r4 <- read.table("mt7.2r2.rp", header = FALSE)
p1=r1[1]
per1=log10(p1)
p2=r2[1]
per2=log10(p2)
p3=r3[1]
per3=log10(p3)
p4=r4[1]
per4=log10(p4)
m1=nrow(per1)
m2=nrow(per2)
m3=nrow(per3)
m4=nrow(per4)
xmin <- floor( min(per1,per2,per3,per4))
xmax <- ceiling( max(per1,per2,per3,per4))
lxmax=10^(xmax)
lxmin=10^(xmin)
rhoaxy = r2[3]
phaxy = r2[5]
rhoayx = r3[3]
phayx = r3[5]
rhoaxx = r1[3]
phaxx = r1[5]
rhoayy = r4[3]
phayy = r4[5]
per2=unname(per2)
per2=unlist(per2)
per3=unname(per3)
per3=unlist(per3)
rhoaxy=unname(rhoaxy)
rhoaxy=unlist(rhoaxy)
rhoaxy=log10(rhoaxy)
rhoayx=unname(rhoayx)
rhoayx=unlist(rhoayx)
rhoayx=log10(rhoayx)
ymin1=floor(min(rhoaxy)-1)
ymax1=ceiling(max(rhoaxy)+1)
ymin2=floor(min(rhoayx)-1)
ymax2=ceiling(max(rhoayx)+1)
ymin=min(ymin1,ymin2)
ymax=max(ymax1,ymax2)
png("withlim.png")
plot(per2,rhoaxy, col='red', xlab='Per (s)', ylab = 'Rho-xy/yx',ylim=c(ymin, ymax))
par(new=TRUE)
plot(per3,rhoayx, col='green', xaxt='n', xlab= NA, yaxt = 'n', ylab = NA)
dev.off()
The image I got
If I delete ylim
My question is,why are the axis limits changing the image content?The values from the second image correspond to proper data values.The first image is with values that do not represent rhoaxy and rhoayx.
It is difficult to test without the data, but my guess is that, on the second plot, the Y axis is not the same, although the Y axis is not plot.
So you've got the superposition of 2 plot, with a different Y axis.
If you want the same ylim on both plot, add ylim=c(ymin, ymax) on the second plot also.
If it does not work, please provide data example, so we can test.
Related
I am planning to reproduce the attached figure, but I have no clue how to do so:
Let´s say I would be using the CO2 example dataset, and I would like to plot the relative change of the Uptake according to the Treatment. Instead of having the three variables in the example figure, I would like to show the different Plants grouped for each day/Type.
So far, I managed only to get this bit of code, but this is far away from what it should look like.
aov1 <- aov(CO2$uptake~CO2$Type+CO2$Treatment+CO2$Plant)
plot(TukeyHSD(aov1, conf.level=.95))
Axes should be switched, and I would like to add statistical significant changes indicated with letters or stars.
You can do this by building it in base R - this should get you started. See comments in code for each step, and I suggest running it line by line to see what's being done to customize for your specifications:
Set up data
# Run model
aov1 <- aov(CO2$uptake ~ CO2$Type + CO2$Treatment + CO2$Plant)
# Organize plot data
aov_plotdata <- data.frame(coef(aov1), confint(aov1))[-1,] # remove intercept
aov_plotdata$coef_label <- LETTERS[1:nrow(aov_plotdata)] # Example labels
Build plot
#set up plot elements
xvals <- 1:nrow(aov_plotdata)
yvals <- range(aov_plotdata[,2:3])
# Build plot
plot(x = range(xvals), y = yvals, type = 'n', axes = FALSE, xlab = '', ylab = '') # set up blank plot
points(x = xvals, y = aov_plotdata[,1], pch = 19, col = xvals) # add in point estimate
segments(x0 = xvals, y0 = aov_plotdata[,2], y1 = aov_plotdata[,3], lty = 1, col = xvals) # add in 95% CI lines
axis(1, at = xvals, label = aov_plotdata$coef_label) # add in x axis
axis(2, at = seq(floor(min(yvals)), ceiling(max(yvals)), 10)) # add in y axis
segments(x0=min(xvals), x1 = max(xvals), y0=0, lty = 2) #add in midline
legend(x = max(xvals)-2, y = max(yvals), aov_plotdata$coef_label, bty = "n", # add in legend
pch = 19,col = xvals, ncol = 2)
This is what I have done so far
library(Hmisc)
m1 <- read.table("mt7.1r1.rp", header = FALSE)
m2 <- read.table("mt7.1r2.rp", header = FALSE)
m3 <- read.table("mt7.2r1.rp", header = FALSE)
m4 <- read.table("mt7.2r2.rp", header = FALSE)
p1=m1[1]
per1=log10(p1)
ixxr=m1[3]
ixxi=m1[4]
p2=m2[1]
per2=log10(p2)
ixyr=m2[3]
ixyi=m2[4]
p3=m3[1]
per3=log10(p3)
iyxr=m3[3]
iyxi=m3[4]
p4=m4[1]
per4=log10(p4)
iyyr=m4[3]
iyyi=m4[4]
erxx=m1[5]
erxy=m2[5]
eryx=m3[5]
eryy=m4[5]
xmin <- floor(min(per1,per2,per3,per4))
xmax <- ceiling(max(per1,per2,per3,per4))
ymin <- floor(min(ixxr,ixxi))
ymax <- ceiling(max(ixxr,ixxi))
per1=unname(per1)
ixxr=unname(ixxr)
ixxi=unname(ixxi)
erxx=unname(erxx)
per1=unlist(per1)
ixxr=unlist(ixxr)
ixxi=unlist(ixxi)
erxx=unlist(erxx)
errbar(per1,ixxr,ixxr+erxx,ixxr-erxx,col='red',xlabel='Per (s)',ylabel='Zxx/Zxy')
par(new = T)
errbar(per1,ixxi,ixxi+erxx,ixxi-erxx,col='green')
But i got image
Y-axis from two datasets are overlapping. How to prevent this?
I want to have a unique axis in min,max range with one single label.
Should I group the data before the plotting or...?
Adding yaxt = 'n' to one of the two plots (I did it for the first one) you do not report the y axis. For having just one y label, use first ylab = NA, then set the y label in the second plot (or viceversa).
errbar(per1,ixxr,ixxr+erxx,ixxr-erxx,col='red', xlab='Per (s)',
yaxt = 'n', ylab = NA)
errbar(per1,ixxi,ixxi+erxx,ixxi-erxx,col='green', ylab = 'ixxr and ixxi')
It would be good practice to compute the common range of the y values and setting it through ylim, so to be sure that everything will be shown on the plot.
This question already has answers here:
How can I plot with 2 different y-axes?
(6 answers)
Closed 6 years ago.
i'm having troubles in a multi axis barplot. I have an X,Y axis with bars and dots in the same graph. The point is that I have to shown both of them in different scales
While I can shown both (bars and dots) correctly, the problem comes when I try to set different scales in left and right axis. I dont know how to change the aditional axis scale, and how to bind the red dots to the right axis, and the bars to the left one.
This is my code and what I get:
labels <- value
mp <- barplot(height = churn, main = title, ylab = "% churn", space = 0, ylim = c(0,5))
text(mp, par("usr")[3], labels = labels, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=.9)
# Population dots
points(popul, col="red", bg="red", pch=21, cex=1.5)
# Churn Mean
media <- mean(churn)
abline(h=media, col = "black", lty=2)
# Population scale
axis(side = 4, col= "red")
ylim= c(0,50)
ylim= c(0,5)
What I want is to have left(grey) axis at ylim=c(0,5) with the bars bound to that axis. And the right(red) axis at ylim=c(0,50) with the dots bound to that axis...
The goal is to represent bars and points in the same graph with diferent axis.
Hope I explained myself succesfully.
Thanks for your assistance!
Here is a toy example. The only "trick" is to store the x locations of the bar centers and the limits of the x axis when creating the barplot, so that you can overlay a plot with the same x axis and add your points over the centers of the bars. The xaxs = "i" in the call to plot.window indicates to use the exact values given rather than expanding by a constant (the default behavior).
set.seed(1234)
dat1 <- sample(10, 5)
dat2 <- sample(50, 5)
par(mar = c(2, 4, 2, 4))
cntrs <- barplot(dat1)
xlim0 <- par()$usr[1:2]
par(new = TRUE)
plot.new()
plot.window(xlim = xlim0, ylim = c(0, 50), xaxs = "i")
points(dat2 ~ cntrs, col = "darkred")
axis(side = 4, col = "darkred")
I have some wind speed and direction data over a course of some time and I need to plot it into a feather plot.
After surfing the web for some time, I find a function someone wrote to plot the feather plot that works for me (Thank you if you are reading this!!). My problem now is that I don't know how to manipulate the labelling of the x-axis.
After the plotting, the figure looks like this:
Now the x-axis doesn't look too bad here, but imagine I have 200 data points (and thus ticks) instead of 10, and the axis ticks can get a bit confusing. So I was hoping someone can help me manipulate the x-axis, specifically messing with the ticks.
The code to plot the figure is:
stg <- scan(what="", sep="\n")
9/20/15_12:00 2.597058824 157.9411765
9/21/15_0:00 2.177192982 185.1754386
9/21/15_12:00 2.577391304 189.2173913
9/22/15_0:00 1.984955752 237.4336283
9/22/15_12:00 3.993859649 252.6315789
9/23/15_0:00 1.613392857 175.5357143
9/23/15_12:00 3.849166667 216.8333333
9/24/15_0:00 2.138135593 117.0338983
9/24/15_12:00 3.32605042 216.302521
9/25/15_0:00 1.490178571 239.8214286
df <- read.table(textConnection(stg), sep="")
colnames(df) <- c("Time", "wsp", "wdir")
df$PTime <- as.POSIXct(df$Time, format="%m/%d/%y_%H:%M")
feather.plot2 <- function (r, theta, xpos, yref = 0, use.arrows = TRUE, col.refline = "lightgray",
fp.type = "s", main = "", xlab = "", ylab = "", xlabels = NULL,
...)
{
if (missing(xpos))
xpos <- 1:length(theta)
if (fp.type == "m")
theta <- 5 * pi/2 - theta
x <- r * cos(theta)
y <- r * sin(theta)
xmult <- diff(range(xpos))/(diff(range(y)) * 2)
x <- x * xmult
xlim <- range(c(xpos, x + xpos))
ylim <- range(c(y, yref))
oldpin <- par("pin")
xdiff <- xlim[2] - xlim[1]
ydiff <- ylim[2] - ylim[1]
plot(0, xlim = xlim, ylim = ylim, type = "n", main = main,
xlab = xlab, ylab = ylab, axes = TRUE, xaxt = "n")
box()
if (is.null(xlabels))
axis(1)
else axis(1, at = xpos, labels = xlabels)
abline(h = yref, col = col.refline)
if (use.arrows)
arrows(xpos, yref, xpos + x, y, length = 0.1, ...)
else segments(xpos, yref, xpos + x, y, ...)
par(pin = oldpin)
}
feather.plot2(df$wsp, df$wdir, fp.type="m", xlabels=df$PTime)
And what I want is something like having big ticks for 12:00, and smaller ticks for 0:00, like in this figure:
Although I don't know why the label for this figure comes out as "Sun - Thu" instead of dates...
The code for this figure is:
daterange=c(min(df$PTime), max(df$PTime))
plot(x=df$PTime, y=df$wsp, xaxt="n", type="l")
axis.POSIXct(1, at=seq(daterange[1], daterange[2], by="day"))
axis.POSIXct(1, at=seq(daterange[1], daterange[2], by="12 hours"), tcl = -0.3, labels=FALSE )
I've tried using using these axis commands on the feather plot, but it did not work. So I'd appreciate any help/advice. Thank you so much!!
I'm seeing two requests: Major and minor ticks; and More compact axis annotation of date-times. Step 1: Suppress the default axis creation. Step 2: The usual manor is to label the major ticks, so we would determine the proper location of those ticks and give a format specification to the labels. Step 3: place the minor tick marks. Most of this you've already figured out, and I would have thought the format problem was the easiest one to solve, so let's see:
plot(x=df$PTime, y=df$wsp, xaxt="n", type="l")
axis.POSIXct(1, at=seq(daterange[1], daterange[2], by="day"), format="%m-%d %H%P",
lwd.ticks=2)
axis.POSIXct(1, at=seq(daterange[1], daterange[2], by="12 hours"),
tcl = -0.3, labels=FALSE )
Seems to succeed at what I think are your goals. The use of by = "day" may be what leads the interpreter to choose the three letter abbrev of day names. (I don't really know.)
I have to plot a physical variable over a world map at differents moments. So i have to make many plot as how many moments i have to plot. The problem is that my routine set the end of the scale by default, and this make the reading of the plot difficult. I would like to fix the end of the scale, in order to have one scale for all the plots. This is piece of an old code i would reuse
require(reshape)
require(mapdata)
require(mapproj)
df <- read.table('/media/Lacie2/dati/hy.dat',head=F)
names(df) <- c("value", "x", "y")#, "t")
dfc <- cast(df[ ,-4], x ~ y)
mm<-as.matrix(dfc,ncol=480,nrow=241)
filled.contour(x=seq(0,360,length.out=480),y=seq(-90,90,length.out=241),mm,
color.palette = colorRampPalette(c("lightblue", "blue","violet", "black")),
xlab = "Longitude (°)", ylab = "Latitude (°)",
plot.axes = {axis(1); axis(2);
map('world2Hires',
xlim = c(0, 360),
ylim = c(-90, 90),
add = T, col = "black")}
)
I don't understand how to fix the endscale of the ladder. How can i do it?
If you want to plot colors only up to a maximum, then just 'trim' the value that you pass to the plot routine with:
df$trimval <- pmin(df$value, 2)
# the range in the example below is roughly -4.5 to 4.5
... and plot using that value as the z-argument to contour.plot. Indented code and random "value" argument below:
require(reshape)
require(mapdata)
require(mapproj)
df <- data.frame(value=rnorm( 480*241), x=seq(0,360,length.out=480),y=seq(-90,90,length.out=241) )
df$trimval <- pmin(df$value, 2)
dfc <- cast(df[-1], x ~ y)
mm<-as.matrix(dfc,ncol=480,nrow=241)
filled.contour(x=seq(0,360,length.out=480),y=seq(-90,90,length.out=241),mm,
color.palette = colorRampPalette(c("lightblue", "blue","violet", "black")),
xlab = "Longitude (°)", ylab = "Latitude (°)",
plot.axes = {axis(1); axis(2);
map('world2Hires',
xlim = c(0, 360),
ylim = c(-90, 90),
add = T, col = "black")}
)
The color range is therefore maxxed out at 2 and all of the values above 2 are plotted with the color given to 2. (I might mention that I tried using zlim and the results were not as I imagined you would want.)