I am trying to plot a chat with two axis, here is the code and attached is the plot,
I have to do two adjustments to it.
I want to plot a line with dots and dots should be middle of the bars
Adjusting right side axis(i.e axis(4)) tick marks should align with left side axix(i.e axis(2))
Code:
Region=c("North","South","East","West")
Sales=sample(500:1000,4)
Change=sample(1:10,4)/10
names(Sales)=Region
names(Change)=Region
barplot(Sales,ylim=c(0,1000))
par(new=T)
plot(Change,type="b",axes=F,ylim=c(0,1))
axis(4)
box()
Regards,
Sivaji
First, save your barplot as some object. So you will get coordinates of the middle points. Then to add line you can use also function lines() and just multiply Change values with 1000.
Then for axis() function supply at= values and labels= the same as at=, just divided by 1000.
x<-barplot(Sales,ylim=c(0,1000))
lines(x,Change*1000,type="b")
axis(4,at=seq(0,800,200),labels=seq(0,800,200)/1000)
You need to play to set the same x-axis in the second plot, you get this info from par("usr").
The xaxs="i" is to set the xlim exactly, by default R increase the xlim a bit to make it better looking.
par(mar=c(5,5,2,5)) # change margins
x = barplot(Sales, ylim=c(0,1000)) # barplot, keep middle points of bars
mtext("Sales", 2, line=3) # first y-axis label
xlim = par("usr")[1:2] # get xlim from plot
par(new=TRUE)
plot.new() # new plot
plot.window(xlim=xlim, ylim=c(0,1), xaxs="i", yaxs="i") # new plot area, same xlim
lines(x,Change,type="b") # the lines in the middle points
axis(4) # secondary y-axis
mtext("Change", 4, line=3) # secondary y-axis label
box()
Related
I would like to plot two graphs in the same plotting region with horizontal grid lines. Each side of the grid lines should give the value for one graph or the other. There should be no y-axis.
The grid() function allows me to simply set the number of bins using the ny= argument. How do I get the corresponding labels to the grid lines? Usually, I would use axis(..., lwd=0) to get the labels. However, the function requires label positions with at=c() and does not feature a ny= argument. Is there a way to automatically set the locations from the number of bins?
Based on Miff's hint below, this should solve the problem.
plot(1:10, axes=FALSE, ylim=c(0,10), ylab="")
par(yaxp=c(0, 10, 5))
axis(2, lwd=0, col.axis="gray")
par(new=TRUE)
plot(60:50, axes=FALSE, ylim=c(50,60), ylab="")
par(yaxp=c(50, 60, 5))
axis(4, lwd=0, col.axis="gray")
grid(NA, NULL)
grid() gets its locations for gridlines from axTicks(), which in turn uses numbers from par("yaxp"). If you modify this parameter (rather than explicitly passing it to grid), the result will then apply to both the grid drawn and the axis. For example:
plot(1:10, axes=FALSE)
axis(2) #Default 4 sections between ticks
par(yaxp=c(par("yaxp")[1:2], 7)) #Lets have seven instead
axis(4)
grid() #Grid now matches with right rather than left
Obviously similar works for the x axis.
How can one force the visualisation of the zero axes y=0, x=0 in R, removing the external ones siding the plot? I want to obtain the same effect that one can have for example in Gnuplot with set xzeroaxis, set yzeroaxis.
You can do this using by suppressing the default axes by using axes=FALSE and then using axis to draw horizontal and vertical lines to represent the axes.
# example plot
plot(-2:2, -2:2, axes=FALSE)
# add yaxis at position zero and rotate labels 45deg
axis(side=2, pos=0, las=1, lty="dashed")
# x axis
axis(side=1, at=c(-2,-1,1,2), pos=0, lty="dashed")
This produces
Actually, I have solved my own question as follows:
f<-function(x) x^3-2*x
# take the axes off first
plot(f,-2,2, axes=FALSE)
# re-set the axes at a given point (pos=0)
axis(1, pos=0, at=c(-2,-1,0,1,2))
axis(2, pos=0, at=c(-4,-2,2,4))
produces the below, which is what I had in mind (labels and the rest can be then adjusted at will).
I'm new to R so forgive me if the problem is obvious.
The problem I've got is that my legend just wont get shown
and there're no errors telling me something is wrong. I've been checking
the documentations for legends and I can't see where I've gone wrong.
The legend code looks like this:
legend(1, g_range[2], c("Client0","Client1"), cex=0.8,
col=c("blue","red"), pch=21:22, lty=1:2);
A note, everything in my graph works, just that the legend isn't drawn!
How is the drawingorder in R? What happens if one of the plots / lines crosses the space where the legend is supposed to be?
Will the line/plot be seen through the legend, will the legend overlap the lines/plot, will the plot/lines "hide" the legend?
Here is the whole code:
#Define the two Clients and their Deficencies
Client0 <- c(0,3.14,3.60,3.41,3.7,3.6,3.6)
Client1 <- c(0,1.26,1.7,4,2.82,3.42,4)
# Calculate range from 0 to max value of cars and trucks
g_range <- range(0, Client0, Client1)
# Graph autos using y axis that ranges from 0 to max
# value in cars or trucks vector. Turn off axes and
# annotations (axis labels) so we can specify them ourself
plot(Client0, type="o", col="blue", ylim=g_range,
axes=FALSE, ann=FALSE)
# Make x axis using Mon-Fri labels
axis(1, at=1:7, lab=c("1","2","3","4","5","6","7"))
# Make y axis with horizontal labels that display ticks at
# every 1 marks. 1*0:g_range[2] is equivalent to c(0,1,2,3).
axis(2, las=1, at=1*0:g_range[2])
# Create box around plot
box()
# Graph trucks with red dashed line and square points
lines(Client1, type="o", pch=22, lty=2, col="red")
# Create a title with a red, bold/italic font
title(main="Deficiencies", col.main="red", font.main=4)
# Label the x and y axes with dark green text
title(xlab="Time", col.lab=rgb(0,0.5,0))
title(ylab="Deficiencies", col.lab=rgb(0,0.5,0))
# Create a legend at (1, g_range[2]) that is slightly smaller
# (cex) and uses the same line colors and points used by
# the actual plots
legend(1, g_range[2]-1, c("Client0","Client1"), cex=0.8,
col=c("blue","red"), pch=21:22, lty=1:2);
When I create the following plot I get unwanted space between the plotting area and the axis (i.e. the white space between the blue box and the x axis. How can I remove this space and make the plotting area flush with the plot axes? Thanks.
xleft<-c(1,2,2.5)
xright<-c(2,2.5,2.75)
ybottom<-c(1,2,2.5)
ytop<-c(2,2.5,2.75)
par(mar = c(15,15,2.75,2.75) + 0.1)
plot(c(1,2.75),c(1,2.75),type="n",main="title",xlab="site.x",ylab="ylab")
rect(xleft,ybottom,xright,ytop,col=c("blue","red","green"))
#Label position along axes
x.label.position<-(xleft+xright)/2
y.label.position<-(ybottom+ytop)/2
#Labels
x.label<-c("Long species Name1","Long species Name2","Long species Name3")
y.label<-c("Long species Name4","Long species Name5","Long species Name5")
text(par()$usr[1]-0.5,y.label.position,y.label,xpd=TRUE,adj=1)
text(y=par()$usr[3]-0.5,x=x.label.position,x.label,xpd=TRUE,adj=1,srt=90)
par(xpd=TRUE)
legend(-0.1,0,legend=c("Species A","Species B","Species C"),fill=c("blue", "red", "green"))
UPDATE
I tried the suggestion from plannapus with my actual data but can only get the y-axis to behave is there some else in this chunk of code that is adding space to the sides of the plotting area?
quartz("colour.plot")
par(mar=c(15,15,4,2)+0.1)#sets margins of plotting area
#create the data plot
plot(c(0,100), c(0,100), type = "n", main = paste(x,"vs",y," -",depth),xlab=paste("Species composition in remainder ",x),ylab=paste("Species composition in remainder ",y),asp=1,xaxs="i",yaxs="i")
#Add the rectangles
rect(mdf$xleft,mdf$ybottom,mdf$xright,mdf$ytop,col=mdf$colour)
produces
There is an argument in function plot that handles that: xaxs (and yaxs for the y-axis).
As default it is set to xaxs="r" meaning that 4% of the axis value is left on each side. To set this to 0: xaxs="i". See the xaxs section in ?par for more information.
plot(c(1,2.75),c(1,2.75),type="n",main="title",xlab="site.x",ylab="ylab", xaxs="i", yaxs="i")
rect(xleft,ybottom,xright,ytop,col=c("blue","red","green"))
plot(c(1,2.75),c(1,2.75),type="n",main="title",xlab="site.x",ylab="ylab",axes=F) # ann
axis(1,pos=1)
axis(2,pos=1)
All axes are remove then you can add new axes to the pos you want.
Hello I am trying to create a stacked barplot using the following code:
test <- as.matrix(read.csv(file="test4.csv",sep=",",head=TRUE))
test <- test[,2:ncol(test)]
pdf(file="test.pdf", height=4, width=6)
par(lwd = 0.3)
barplot(test, space=0.4, xaxt='n', ann=FALSE)
axis(1, cex.axis=0.25, las=2, at=1:ncol(test), space=0.4, labels=colnames(test))
dev.off()
And I get:
As you can see the labels in the x-axis do not match the bars in the plot. Also, the ticks are huge.
Can you guys help me beautify the x axis? Thanks so much
Try storing the returned value of the call to barplot() in a named object, and then passing that in to the at= argument of axis():
xLabLocs <- barplot(test, space=0.4, xaxt='n', ann=FALSE)
axis(1, cex.axis=0.25, las=2, at=xLabLocs,
space=0.4, labels=colnames(test))
This may look odd, but it is explained in the Value section of the ?barplot help file:
Value:
A numeric vector (or matrix, when ‘beside = TRUE’), say ‘mp’,
giving the coordinates of _all_ the bar midpoints drawn, useful
for adding to the graph.
You just made the (easy enough to make) mistake of assuming that the x-axis coordinates of the bar centers are at 1:n, where n is the number of bars. That's not necessarily true, so it's nice that a single call to barplot() will both: (a) plot the bar plot as its side effect; and (b) return the necessary x-axis coordinates as its return value.