简体   繁体   中英

Making a grouped bar chart using a matrix in R

I am trying to make a grouped bar chart using numeric type data in the form of a matrix. The data frame I am pulling from has the data stored as strings so I also need to transform the data to the numeric type.

making vectors

wt250 <- c(as.numeric(df$WT.250[which(df$X=="Ifng")]), as.numeric(df$WT.250[which(df$X=="Prdm1")]), as.numeric(df$WT.250[which(df$X=="Il2ra")]), as.numeric(df$WT.250[which(df$X=="Cd69")]) wt50 <- c(as.numeric(df$WT.50[which(df$X=="Ifng")]), as.numeric(df$WT.50[which(df$X=="Prdm1")]), as.numeric(df$WT.50[which(df$X=="Il2ra")]), as.numeric(df$WT.50[which(df$X=="Cd69")])) wt10 <- c(as.numeric(df$WT.10[which(df$X=="Ifng")]), as.numeric(df$WT.10[which(df$X=="Prdm1")]), as.numeric(df$WT.10[which(df$X=="Il2ra")]), as.numeric(df$WT.10[which(df$X=="Cd69")])

making the matrix

m <- matrix(c(wt250, wt50, wt10), nrow=3, ncol=4, byrow = TRUE)

vectors for details of the bar plot

names <- c("WT-250", "WT-50", "WT-10") colors <- c("red", "orange", "yellow", "green")

graphing the bar plot

barplot(m, main = "Genes", ylab = "Concentration", names.arg = names, col = colors, beside = TRUE)

I expect a grouped bar chart (multiple bars that are adjacent to each other) with WT-250, WT-50, and WT-10 on the x axis which 4 bars each in the colors red, orange, yellow, and green. Instead, I get the following error message: Error in -0.01 * height : non-numeric argument to binary operator

If you want a quick fix replace your matrix creation:

m <- matrix(c(wt250, wt50, wt10), nrow=3, ncol=4, byrow = TRUE)

by

m <- matrix(c(wt250, wt50, wt10), nrow=4, ncol=3)

So that you now have your vectors in columns.

Instead of "names" use "colnames". Then your code should work, and barplot will be able to plot what you want.

Example :

mat <- matrix(1:12, nrow = 4, ncol = 3)
colnames(mat) <- letters[1:3]
rownames(mat) <- letters[23:26]

barplot(mat,col = c("red", "blue", "cyan", "orange"), beside = TRUE)

Grouped_bar_chart

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM