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
andtext.width
for reduce the size of the legend.Here an example:
And same code modifiying the
legend
function: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.