This is probably a simple question, but I´m not able to find the solution for this.
I have the following plot (I´m using plot CI since I´m not able to fill the points with plot()).
leg<-c("1","2","3","4","5","6","7","8")
Col.rar1<-c(rgb(1,0,0,0.7), rgb(0,0,1,0.7), rgb(0,1,1,0.7),rgb(0.6,0,0.8,0.7),rgb(1,0.8,0,0.7),rgb(0.4,0.5,0.6,0.7),rgb(0.2,0.3,0.2,0.7),rgb(1,0.3,0,0.7))
library(plotrix)
plotCI(test$size,test$Mean,
pch=c(21), pt.bg=Col.rar1,xlab="",ylab="", ui=test$Mean,li= test$Mean)
legend(4200,400,legend=leg,pch=c(21),pt.bg=Col.rar1, bty="n", cex=1)
I want to creat the same effect but with lines, instead of points (continue line)
Any suggestion?
You have 2 solutions :
Use The lines() function draws lines between (x, y) locations.
Use plot with type = "l" like line
hard to show it without a reproducible example , but you can do for example:
Col.rar1<-c(rgb(1,0,0,0.7), rgb(0,0,1,0.7), rgb(0,1,1,0.7),rgb(0.6,0,0.8,0.7),rgb(1,0.8,0,0.7),rgb(0.4,0.5,0.6,0.7),rgb(0.2,0.3,0.2,0.7),rgb(1,0.3,0,0.7))
x <- seq(0, 5000, length.out=10)
y <- matrix(sort(rnorm(10*length(Col.rar1))), ncol=length(Col.rar1))
plot(x, y[,1], ylim=range(y), ann=FALSE, axes=T,type="l", col=Col.rar1[1])
lapply(seq_along(Col.rar1),function(i){
lines(x, y[,i], col=Col.rar1[i])
points(x, y[,i]) # this is optional
})
When it comes to generating plots where you want lines connected according to some grouping variable, you want to get away from base-R plots and check out lattice and ggplot2. Base-R plots don't have a simple concept of 'groups' in an xy plot.
A simple lattice example:
library( lattice )
dat <- data.frame( x=rep(1:5, times=4), y=rnorm(20), gp=rep(1:4,each=5) )
xyplot( y ~ x, dat, group=gp, type='b' )
You should be able to use something like this if you have a variable in test similar to the color vector you define.
Related
I'm doing stochastic dominance analysis with diferent income distributions using Pen's Parade. I can plot a single Pen's Parade using Pen function from ineq package, but I need a visual comparison and I want multiple lines in the same image. I don't know how extract values from the function, so I can't do this.
I have the following reproducible example:
set.seed(123)
x <- rnorm(100)
y <- rnorm(100, mean = 0.2)
library(ineq)
Pen(x)
Pen(y)
I obtain the following plots:
I want obtain sometime as the following:
You can use add = TRUE:
set.seed(123)
x <- rnorm(100)
y <- rnorm(100, mean = 0.2)
library(ineq)
Pen(x); Pen(y, add = TRUE)
From help("Pen"):
add logical. Should the plot be added to an existing plot?
While the solution mentioned by M-M in the comments is a more general solution, in this specific case it produces a busy Y axis:
Pen(x)
par(new = TRUE)
Pen(y)
I would generalize the advice for plotting functions in this way:
Check the plotting function's help file. If it has an add argument, use that.
Otherwise, use the par(new = TRUE) technique
Update
As M-M helpfully mentions in the comments, their more general solution will not produce a busy Y axis if you manually suppress the Y axis on the second plot:
Pen(x)
par(new = TRUE)
Pen(y, yaxt = "n")
Looking at ?ineq::Pen() it seems to work like plot(); therefore, followings work for you.
Pen(x)
Pen(y, add=T)
Note: However, add=T cuts out part of your data since second plot has points which fall out of the limit of the first.
Update on using par(new=T):
Using par(new=T) basically means overlaying two plots on top of each other; hence, it is important to make them with the same scale. We can achieve that by setting the same axis limits. That said, while using add=T argument it is desired to set limits of the axis to not loose any part of data. This is the best practice for overlaying two plots.
Pen(x, ylim=c(0,38), xlim=c(0,1))
par(new=T)
Pen(y, col="red", ylim=c(0,38), xlim=c(0,1), yaxt='n', xaxt='n')
Essentially, you can do the same with add=T.
I found some similar questions but the answers didn't solve my problem.
I try to plot a time series of to variables as a scatterplot and using the date to color the points. In this example, I created a simple dataset (see below) and I want to plot all data with timesteps in the 1960ties, 70ties, 80ties and 90ties with one colour respectively.
Using the standard plot command (plot(x,y,...)) it works the way it should, as I try using the ggplot library some strange happens, I guess I miss something. Has anyone an idea how to solve this and generate a correct plot?
Here is my code using the standard plot command with a colorbar
# generate data frame with test data
x <- seq(1,40)
y <- seq(1,40)
year <- c(rep(seq(1960,1969),2),seq(1970,1989,2),seq(1990,1999))
df <- data.frame(x,y,year)
# define interval and assing color to interval
myinterval <- seq(1959,1999,10)
mycolors <- rainbow(4)
colbreaks <- findInterval(df$year, vec = myinterval, left.open = T)
# basic plot
layout(array(1:2,c(1,2)),widths =c(5,1)) # divide the device area in two panels
par(oma=c(0,0,0,0), mar=c(3,3,3,3))
plot(x,y,pch=20,col = mycolors[colbreaks])
# add colorbar
ncols <- length(myinterval)-1
colbarlabs <- seq(1960,2000,10)
par(mar=c(5,0,5,5))
image(t(array(1:ncols, c(ncols,1))), col=mycolors, axes=F)
box()
axis(4, at=seq(0.5/(ncols-1)-1/(ncols-1),1+1/(ncols-1),1/(ncols-1)), labels=colbarlabs, cex.axis=1, las=1)
abline(h=seq(0.5/(ncols-1),1,1/(ncols-1)))
mtext("year",side=3,line=0.5,cex=1)
As I would like to use ggplot package, as I do for other plots, I tried this version with ggplot
# plot with ggplot
require(ggplot2)
ggplot(df, aes(x=x,y=y,color=year)) + geom_point() +
scale_colour_gradientn(colours= mycolors[colbreaks])
but it didn't work the way I thought it would. Obviously, there is something wrong with the color coding. Also, the colorbar looks strange. I also tried it with scale_color_manual and scale_color_gradient2 but I got more errors (Error in continuous_scale).
Any idea how to solve this and generate a plot according to the standard plot 3 including a colorbar.
I know most of the programers would refer me to 'LATTICE' or 'ggplot2' packages of R as a solution to this question, but there must be a way to do it with the base package. I want to plot multiple graphs with corresponding regression lines and correlation coefficients with simple loops. An easy example data may look like-
a=list(cbind(c(1,2,3), c(4,8,12)), cbind(c(5,15,25), c(10,30,50)))
par(mfrow=c(1,2))
lapply(1:length(a), function(i)
plot(a[[i]][,1], a[[i]][,2]))
lapply(1:length(a), function(i)
abline(lm(a[[i]][,2]~a[[i]][,1])))
require(plotrix)
lapply(1:length(a), function(i)
boxed.labels(a[[i]][,1][1], a[[i]][,2][3],
labels=paste(round(cor(a[[i]][,2], a[[i]][,1], use = "pairwise.complete.obs"),2)),
border=FALSE, adj=0.5, cex=0.8))
If you run the above script you'd notice that all linear lines and r-values will plot on the top of the last graph. Is there any way to write in the call for regression along with the plot command? Or any other clever way to deal with loops to plot regressions on corresponding figures?? It works fine for a single plot (shown below), but I'm working with a considerably large list!
plot(a[[1]][,1], a[[1]][,2])
abline(lm(a[[1]][,2]~a[[1]][,1]))
boxed.labels(a[[1]][,1][1], a[[1]][,2][3],
labels=paste(round(cor(a[[1]][,2], a[[1]][,1], use = "pairwise.complete.obs"),2)),
border=FALSE, adj=0.5, cex=0.8)
Once you call plot(), you start drawing in a new "cell". So if you want to add more to the plot before moving on to the next one, make sure you do all of your drawing before calling the next plot()
For example
a=list(cbind(c(1,2,3), c(4,8,12)), cbind(c(5,15,25), c(10,30,50)))
par(mfrow=c(1,2))
lapply(a, function(d) {
d <- setNames(data.frame(d), c("x","y"))
plot( y~x, d )
abline( lm( y ~ x, d ) )
boxed.labels(min(d$x), max(d$y),
labels=paste(round(cor(d$y, d$x, use = "pairwise.complete.obs"),2)),
border=FALSE, adj=0.5, cex=0.8)
})
Note how we do all the drawing inside a single lapply() so that abline and boxed.labels are called in between the multiple plot calls rather than after they are all done.
I am trying to plot several points with error bars, with two y axes.
However at every call of the plotCI or errbar functions, a new plot is initialized - with or without par(new=TRUE) calls -.
require(plotrix)
x <- 1:10
y1 <- x + rnorm(10)
y2<-x+rnorm(10)
delta <- runif(10)
plotCI(x,y=y1,uiw=delta,xaxt="n",gap=0)
axis(side=1,at=c(1:10),labels=rep("a",10),cex=0.7)
par(new=TRUE)
axis(4)
plotCI(x,y=y2,uiw=delta,xaxt="n",gap=0)
I have also tried the twoord.plot function from plotrix, but I don't think it's possible to add the error bars.
With ggplot2 I have only managed to plot in two different panels with the same Y axis.
Is there a way to do this?
Use add=TRUE,
If FALSE (default), create a new plot; if TRUE, add error bars to an
existing plot.
For example the last line becomes:
plotCI(x,y=y2,uiw=delta,xaxt="n",gap=0,add=TRUE)
PS: hard to do this with ggplot2. take a look at this hadley code
EDIT
The user coordinate system is now redefined by specifying a new user setting. Here I do it manually.
plotCI(x,y=y1,uiw=delta,xaxt="n",gap=0)
axis(side=1,at=c(1:10),labels=rep("a",10),cex=0.7)
usr <- par("usr")
par(usr=c(usr[1:2], -1, 20))
plotCI(x,y=y2,uiw=delta,xaxt="n",gap=0,add=TRUE,col='red')
axis(4,col.ticks ='red')
I have 3 models, all of which are significant and I want to create a linear graph with my data. This is what I have so far:
>morpho<-read.table("C:\\Users\\Jess\\Dropbox\\Monochamus\\Morphometrics.csv",header=T,sep=",")
> attach(morpho)
> wtpro<-lm(weight~pronotum)
> plot(weight,pronotum)
> abline(wtpro)
I have tried entering the abline as:
abline(lm(weight~pronotum))
I can't figure out what I'm doing wrong. I want to add my equation, I have all of my coefficients but can't get past the line...I have even started over thinking maybe I messed up along the way and it still will not work. Is there a separate package that I am missing?
Try:
abline(coef(lm(weight~pronotum)) # works if dataframe is attached.
I try to avoid attach(). It creates all sorts of anomalies that increase as you do more regression work. Better would be:
wtpro<-lm(weight~pronotum, data= morpho)
with( morpho , plot(weight,pronotum) )
abline( coef(wtpro) )
Plot is in the format plot(x, y, ...) and it looks like you've ordered your dependent variable first. Easy mistake to make.
For example:
Set up some data
y <- rnorm(10)
x <- rnorm(10) + 5
A plot with the dependent variable placed on the x axis will not display the regression line as it's outside of the visible plane.
plot(y,x)
abline(lm(y~x), col='red', main='Check the axis labels')
Flip the variables in the plot command. Now it will be visible.
plot(x,y)
abline(lm(y~x), col='red', main='Check the axis labels')