Is there a way in base R to manually add a second barplot to an existing one. I know how to do it if the two series are from the same data object (using barplot( ... beside=T)) or I guess one could draw rectangles (rect(...)) which barplot wraps. If your data is from different objects how can you then do it with the barplot function ? How to control bar positions?
I tried this using the space parameter (obviously not working):
h1 <- c(10,5,1)
h2 <- c(8, 3, 1)
barplot(h1, width = 0.5, space = 2, col='red')
barplot(h2, width = 0.5, space = 2.5, col='blue', add=T)
It is impossible to get the bars besides each other as when using the beside=T argument.
Desired output is something along this:
barplot(matrix(c(h1, h2), nrow=2, byrow=T), beside=T, col=c('red', 'blue'))
UPDATE: how it works
In order for me to finally - I hope - understand the width and space arguments, we can plot an axis and play with the parameters for the blue data.
barplot(h1, width = 0.5, space = 2, col='red')
axis(1, seq(0, 10, 0.5)) #way out of the plot region
barplot(h2, width = 0.25, space = c(4,2,4), col='blue', add=T)
From this it seem as (correct me if I am wrong):
1. width is the width of each bar - recycled as necessary
2. space controls the space to the previous bar (to the left) or to 0 for the first bar, and is calculated as width*space for the current bar - recycled as necessary. So the first blue bar starts at (space to 0) 0.25*4 = 1 and its right side is at 1+0.25 = 1.25; the second bar starts at 1.25+0.25*2 = 1.75, and its right side is at 1.75+0.25 = 2. And so forth...
You can do this:
h1 <- c(10,5,1)
h2 <- c(8, 3, 1)
barplot(h1, width = 0.5, space = 2, col='red')
barplot(h2, width = 0.5, space = c(3,2,2), col='blue', add=T)
And this will be the output:
Related
I have been unable to find a way to adjust the (vertical) distance between plot and main title in R using par. In this example:
plot(1, 1, main = "Title")
I can adjust the position of the axis titles using:
par(mgp = c(2.5, 1, 0))
But I see no way to similarly adjust the main title. I am aware that more manual control is possible using title or mtext, but I assume that there is a way setting the title distance using par as well, which would be more elegant for my purposes.
We can use title() function with negative line value to bring down the title.
See this example:
plot(1, 1)
title("Title", line = -2)
To summarize and explain visually how it works. Code construction is as follows:
par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)
explanation:
par(mar = c(low, left, top, right)) - margins of the graph area.
title("text" - title text
adj = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
line = positive values move title text up, negative - down)
Try this:
par(adj = 0)
plot(1, 1, main = "Title")
or equivalent:
plot(1, 1, main = "Title", adj = 0)
adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.
However, the issue is that this will also change the position of the label of the x-axis and y-axis.
I have been unable to find a way to adjust the (vertical) distance between plot and main title in R using par. In this example:
plot(1, 1, main = "Title")
I can adjust the position of the axis titles using:
par(mgp = c(2.5, 1, 0))
But I see no way to similarly adjust the main title. I am aware that more manual control is possible using title or mtext, but I assume that there is a way setting the title distance using par as well, which would be more elegant for my purposes.
We can use title() function with negative line value to bring down the title.
See this example:
plot(1, 1)
title("Title", line = -2)
To summarize and explain visually how it works. Code construction is as follows:
par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)
explanation:
par(mar = c(low, left, top, right)) - margins of the graph area.
title("text" - title text
adj = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
line = positive values move title text up, negative - down)
Try this:
par(adj = 0)
plot(1, 1, main = "Title")
or equivalent:
plot(1, 1, main = "Title", adj = 0)
adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.
However, the issue is that this will also change the position of the label of the x-axis and y-axis.
I'm using plot() to create a map with a legend and because of the shape of the map, it overlaps with the legend. I'm still learning R, but how can I move the map slightly to the left to reduce overlap? I'm sure there's a simple fix, but I was not able to find the right parameter.
Thanks for your help! I'm new to R (and stackoverflow) so I cannot post an image unfortunately.
EDIT: Here's the code that I'm running:
plot(spdfCounties, bg="gray90", col=findColours(ciFisher, colRamp))
title("Fisher-Jenks")
strLegend = paste(
"$", format(round(ciFisher$brks[-(intClasses + 1)]), big.mark=","), " - ",
"$", format(round(ciFisher$brks[-1]), big.mark=","), sep=""
)
legMain = legend(
"topright", legend=strLegend,
title="Median Income, 2010", bg="gray", inset=0.02, cex=0.6,
fill=colRamp
)
Use the mar (for margin) options in par. From ?par
mar A numerical vector of the form c(bottom, left, top, right) which
gives the number of lines of margin to be specified on the four sides
of the plot. The default is c(5, 4, 4, 2) + 0.1.
So, if your legend is on the right, make your right margin bigger by entering
par(mar = c(5, 4, 4, 8) + 0.1)
Some trial and error should be able to get it right.
This question about resetting par values may also be helpful. In general, you can always do dev.off() to close the device, and a new device will start with the default par settings.
EDIT: Adapting #Hugh's example
x <- runif(1000)
y <- runif(1000)
plot(x, y)
legend('topright', legend = "points") # overlaps points
par(mar = c(5, 4, 4, 8) + 0.2)
plot(x, y)
legend('right', legend = "points", inset = -.3, xpd = T)
# The correct right margin and inset value will depend
# on the size of your graphic device.
Adjusting the margins results in
Adding white space to the graph, as in #Hugh's answer, looks like this:
Edit 2
Trying to adapt new code from question. You're still using base graphics' plot function, so nothing should be special about having a map. However, we don't have your data, so we can't really test anything. (If this doesn't work---and regardless before posting another question---you should look at tips for making reproducible examples.)
dev.off() # to reset par
par(mar = c(5, 4, 4, 8))
plot(spdfCounties, bg="gray90", col=findColours(ciFisher, colRamp))
# the margins are set as soon as you call plot()
title("Fisher-Jenks")
strLegend = paste(
"$", format(round(ciFisher$brks[-(intClasses + 1)]), big.mark=","), " - ",
"$", format(round(ciFisher$brks[-1]), big.mark=","), sep=""
)
legMain = legend(
"right", # changed the legend to right
legend=strLegend,
title="Median Income, 2010",
bg="gray",
inset= -0.3, # negative inset to put it outside of the plotting region
xpd = T, # xpd set to allow plotting outside of the plot region
cex=0.6,
fill=colRamp
)
As a one off, you can change the lim arguments of plot to create more space.
x <- runif(1000)
y <- runif(1000)
plot(x,y)
legend('topright', legend = "points") # overlaps points
plot(x,y, xlim = c(0, 1.5), ylim = c(0, 1.5) # adds white space
legend('topright', legend = "points")
I have been unable to find a way to adjust the (vertical) distance between plot and main title in R using par. In this example:
plot(1, 1, main = "Title")
I can adjust the position of the axis titles using:
par(mgp = c(2.5, 1, 0))
But I see no way to similarly adjust the main title. I am aware that more manual control is possible using title or mtext, but I assume that there is a way setting the title distance using par as well, which would be more elegant for my purposes.
We can use title() function with negative line value to bring down the title.
See this example:
plot(1, 1)
title("Title", line = -2)
To summarize and explain visually how it works. Code construction is as follows:
par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)
explanation:
par(mar = c(low, left, top, right)) - margins of the graph area.
title("text" - title text
adj = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
line = positive values move title text up, negative - down)
Try this:
par(adj = 0)
plot(1, 1, main = "Title")
or equivalent:
plot(1, 1, main = "Title", adj = 0)
adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.
However, the issue is that this will also change the position of the label of the x-axis and y-axis.
I am creating a boxplot in R with the following code:
boxplot(perc.OM.y ~ Depth, axes = F, ylim = c(-0.6, 0.2), xlim = c(3.5, 5.5),
lwd = 0.1, col = 8,
ylab = "Loss of Percent Organic Matter per Year", cex.lab = 1.5)
axis(1, at = c(3.5, 4, 5, 5.5), labels = c(" ", "Shallow", "Deep", " "),
cex.axis = 1.5)
axis(2, cex.axis = 1.5)
The problem is that the number labels on the y-axis currently overlap the axis title. Is there a way to put more space between the axis title and the axis number labels?
Thanks
## dummy data
dat <- data.frame(Depth = sample(c(3:6), 20, replace = TRUE), OM = 5 * runif(20))
Add some room for the y-axis labels and annotations, by making the margin bigger on the left hand side of the plot (side = 2):
## margin for side 2 is 7 lines in size
op <- par(mar = c(5,7,4,2) + 0.1) ## default is c(5,4,4,2) + 0.1
Now plot:
## draw the plot but without annotation
boxplot(OM ~ Depth, data = dat, axes = FALSE, ann = FALSE)
## add axes
axis(1, at = 1:4, labels = c(" ", "Shallow", "Deep", " "), cex.axis = 1.5)
axis(2, cex.axis = 2)
## now draw the y-axis annotation on a different line out from the plot
## using the extra margin space:
title(ylab = "Loss of Percent Organic Matter per Year", cex.lab = 1.5,
line = 4.5)
## draw the box to finish off
box()
Then reset the plotting margins:
par(op)
This gives:
So we've created more space for the margin of the plot on side 2, and then drawn the axes and the annotation (ylab) separately to control how the plot is spaced out.
So the key to this is this line:
op <- par(mar = c(5,7,4,2) + 0.1) ## default is c(5,4,4,2) + 0.1
What we do is save the original graphical parameters in object op, and change the margin sizes (in numbers of lines) to be 5, 7, 4, 2 + 0.1 lines each for the bottom , left, top, right margins respectively. The line above shows the defaults, so the code gives 2 more lines on the left margin than usually provided by default.
Then when we draw the y-axis label using title(), we specify which line (of the 7) to draw the label at:
title(ylab = "Loss of Percent Organic Matter per Year", cex.lab = 1.5,
line = 4.5)
Here I used line 4.5, but 5 would work also. The greater the values of 'line' the farther from the plot the label is drawn.
The trick is to find the value for the left margin and the value of 'line' in the title() call that allows the axis tick marks and the axis label to not overlap. Trial and error is likely the best solution to find the values you need with base graphics.
Try setting the first value of mgp larger. You'll want to make the margins bigger too, with mar.
par(mgp=c(5,1,0))
par(mar=c(5,6,4,2)+0.1)
I just found this solution very straightforward and useful when I wanted to shrink the white space around the diagram (consider size limits in the conference papers!) while I wanted to avoid overlapping Y-axes title and big numbers as the ticks.
I use to set the titles as text and put them wherever I want, after setting the margins manually:
First, set the margins to the arbitrary values:
par( mar=c(m1, m2, m3, m4) )
where m1 to m4 are margins for four sides (1=bottom, 2=left, 3=top and 4=right).
For example:
par( mar=c(3.1, 4.7, 2.3, 0))
Then, when plotting, set main="", xlab="" and ylab="" (otherwise their text will overlap with this new text)
Finally, using mtext(), set the axis titles and diagram title manually:
mtext(side=1, text="X axes title", line=0.5)
mtext(side=2, text="Y axes title", line=3)
mtext(side=3, text="Diagram title", line=1.5)
The line parameter is the distance from the diagram (the smaller values puts it closer to the diagram).