I am very new to R, so I'm struggling here a bit and I haven't found an answer to my problem.
I'm trying to produce a simple bar-chart in R, and I have set my x-axis variable labels to be vertical, using las=2
. I then changed the margins for the barplot so that the labels would not overlap the xlab label, using par(mar=c(20,15,5,3))
and par(mgp=c(6,1,0))
.
I would like to add a legend to this, but the one I have has adopted the margin dimensions of the graph itself, so that it appears too big and does not fit. I tried using cex
but that only affects the text in the legend. Is there anyway for me to change the legend margins (or the graph margins) independently?
Here's what I have coded:
par(mar=c(20,15,5,3))
par(mgp=c(6,1,0))
par(xpd=TRUE)
barplot(
names.arg=c("Africa", "Central America, South America, Caribbean",
"Middle East", "Central and Eastern Europe",
"South and East Asia"),
cex.names=0.8, las=2, t(YLL),
ylab="Percentage (%)", ylim=c(0,100), main="", beside=TRUE,
col= c("green4", "orange"),xlab="Regions", mar=c(20,15,5,3)
)
legend(
10, 100,
legend=c("Communicable diseases", "Communicable diseases"),
fill= c("green4", "orange"), cex=0.7
)
I will really appreciate the help, thanks.
You can also use the arguments of legend
function: y.intersp
, x.intersp
and text.width
for reduce the size of the legend.
Here an example:
set.seed(55) # Set the seed of R‘s random number generator
x <- 1:10
y <- runif(10, min=0, max=100) # Generating random numbers
z <- runif(10, min=0, max=100) # Generating random numbers
plot(x,y, type="l", ylim=c(0,100), ylab="y and z")
par(new=TRUE)
plot(x,z, type="l", col="red", ylim=c(0,100), ylab=NA, xaxt='n', yaxt='n')
legend("topright", c("y","z"), lty="solid", col=c("black", "red"))
And same code modifiying the legend
function:
set.seed(55) # Set the seed of R‘s random number generator
x <- 1:10
y <- runif(10, min=0, max=100) # Generating random numbers
z <- runif(10, min=0, max=100) # Generating random numbers
plot(x,y, type="l", ylim=c(0,100), ylab="y and z")
par(new=TRUE)
plot(x,z, type="l", col="red", ylim=c(0,100), ylab=NA, xaxt='n', yaxt='n')
legend("topright", c("y","z"), lty="solid", col=c("black", "red"), y.intersp=0.5,x.intersp=0.5,text.width=0.1)
I don't know if I understood your problem correctly, but maybe you can try x.intersp or y.intersp to modify the spacing in the x and y axis of your legend. For example, you could add x.intersp=0.5 to bring the elements of your legend closer in the x axis.
If this does not work and you provide a screenshot, maybe I could try to help you better.