I have a matrix containing some data which I have plotted to a barchart however when observing the barchart result the data appears incorrect. For example, a3
bar should be a value of 12 but it appears to go above 15 on the barchart. Quite new to R programming and would appreciate any insight into where I might be going wrong.
R
colors = c("blue","purple","brown")
assettypes <- c("a1","a2","a3","a4","a5", "a6")
groups <- c("c1","c2")
Values <- matrix(c(3,6,4,3,4,6,
12,9,12,12,11,9), nrow = 2, ncol = 6, byrow = TRUE)
barplot(Values, main = "C1 vs C2", names.arg = assettypes, xlab = "Assets", ylab = "Amount", col = colors)
legend("topleft", groups, cex = 1.3, fill = colors)
CodePudding user response:
Perhaps a dodged barplot is required? Add beside = TRUE
to the call to barplot (always worth checking the function help ?barplot
).
Note:
- removed "brown" from colors as it seems as if there are only two groups in the dataset.
- moved the legend so that it does not overlap the bars.
colors = c("blue","purple")
barplot(Values, main = "C1 vs C2", names.arg = assettypes, xlab = "Assets", ylab = "Amount", col = colors, beside = TRUE)
legend("topright", groups, cex = 1, fill = colors)
CodePudding user response:
The code works fine and the values are stacked correctly. In order to avoid any possible misunderstanding, I changed the names of the groups to row 1
and row 2
.
Sample code:
bb<-barplot(Values,
main = "Row 1 vs Row 2",
names.arg = assettypes,
xlab = "Assets",
ylab = "Amount",
col = colors,
ylim = c(0, 20))
legend("top", groups, cex = 1.3, fill = colors)
text(bb,Values [1,] 4,labels=Values [1,],font=2, cex=.8)
text(bb,colSums(Values)-13,labels=Values[2,],font=2, cex=0.8)
Sample data:
colors = c("blue","purple")
assettypes <- c("a1","a2","a3","a4","a5", "a6")
groups <- c("row 1","row 2")
Values <-matrix(c(3,6,4,3,4,6,
12,9,12,12,11,9),
nrow = 2, ncol = 6, byrow = TRUE)
Values
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 3 6 4 3 4 6
[2,] 12 9 12 12 11 9