Reputation: 753
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)
Upvotes: 1
Views: 164
Reputation: 2282
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
Upvotes: 1
Reputation: 41285
I think the stacked barplot plots the data right. Let's have a look at your Values:
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)
Output Values:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 3 6 4 3 4 6
[2,] 12 9 12 12 11 9
As you can see, a3
is 4+12 which means that it is 16. All other values are combined 15. So that is why the plot is right.
barplot(Values, main = "C1 vs C2", names.arg = assettypes, xlab = "Assets", ylab = "Amount", col = colors, beside=FALSE)
legend("topleft", groups, cex = 1.3, fill = colors)
Output barplot:
Upvotes: 1
Reputation: 12699
Perhaps a dodged barplot is required? Add beside = TRUE
to the call to barplot (always worth checking the function help ?barplot
).
Note:
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)
Created on 2022-03-13 by the reprex package (v2.0.1)
Upvotes: 1