Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify the legend of my barplot in R?

In this barplot, the legend is blocking off a portion of it. How can I reduce the size of the legend?

My code:

`work.gender.marriage.table = table(work$marriage,work$gender)`

enter image description here

`barplot(work.gender.marriage.table,main = "Gender & Marriage",
beside = TRUE,
legend = rownames(work.gender.marriage.table))`

My data:

`structure(list(marriage = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L),    class = "factor", .Label = c("D", "M", "NM", "W")), gender = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("F", "M"), class = "factor"), val = c(12L, 61L, 78L, 56L, 71L, 33L, 86L, 93L)), .Names = c("marriage", "gender", "val"), row.names = c(NA, -8L), class = "data.frame")`

This is the image after using the code:

 barplot(work.gender.marriage.table,main = "Gender & Marriage",
 beside = TRUE)

 legend("topright", 
        legend = rownames(work.gender.marriage.table), 
        ncol = 2,
        cex = 0.5)

Image:enter image description here

like image 225
Natalia Khodayari Avatar asked Jul 03 '17 03:07

Natalia Khodayari


2 Answers

Try this:

barplot(work.gender.marriage.table,main = "Gender & Marriage",
beside = TRUE)

Then add your legend as:

legend("topright", 
       legend = rownames(work.gender.marriage.table), 
       ncol = 2,
       cex = 0.5)

Based on your data:

df = structure(list(marriage = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), class = "factor", .Label = c("D", "M", "NM", "W")), gender = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("F", "M"), class = "factor"), val = c(12L, 61L, 78L, 56L, 71L, 33L, 86L, 93L)), .Names = c("marriage", "gender", "val"), row.names = c(NA, -8L), class = "data.frame")
df


dfM <- df[which(df$gender=="M"),]
dfF <- df[which(df$gender=="F"),]
dfN <- cbind(dfM[,3], dfF[,3])
colnames(dfN) <- c("M", "F")
rownames(dfN) <- dfM$marriage
dfN

barplot(dfN, beside=T, legend.text = rownames(dfN),
        args.legend = list(x = "topleft", bty="n", cex = 0.7, ncol = 2))

enter image description here

like image 66
AK88 Avatar answered Nov 14 '22 22:11

AK88


You could use ggplot2 as well.

library(ggplot2)
ggplot(work.gender.marriage.table) + 
  geom_bar(aes(y = val, x = cat), stat="identity") + facet_grid(. ~ sex)

Example data.frame:

work.gender.marriage.table <- data.frame(cat = c("D", "M", "NM", "W", "D", "M", "NM", "W"),
                                         sex = rep(c("M","F"), each = 4),
                                         val = sample(1:100,8))

enter image description here

like image 32
Edgar Santos Avatar answered Nov 15 '22 00:11

Edgar Santos