How did ggplot evade the chart using stat = "identity"?

I have a data frame with two columns, A and B. I want to create a bar chart with the values ​​in A and B plotted side by side (evasion). I googled around and found ggplot from the ggplot2 package. By default, histogram generation using frequencies is used, but there is an option stat="identity" , which allows you to select a variable to set the column height explicitly. I can build one column as follows:

 d <- data.frame(A=c(1:10), B=c(11:20)) ggplot(data=d, aes(x=1:length(A), y=A))+geom_bar(stat="identity", position="dodge") 

How do I build two columns side by side? I can structure my data frame in different ways: add values ​​from vectors A and B to one column and create indicator variable ind , and then use it to define aes(group=ind) groups aes(group=ind) . Can this be done with the d as-is data frame without changing its structure?

+7
source share
2 answers

You can use the melt from the reshape2 package to create the graph as you look.

 library(reshape2) d$ind <- seq_along(d$A) dm <- melt(d, id.var='ind') ggplot(dm, aes(x=ind, y=value, fill=variable)) + geom_bar(stat='identity', position='dodge') 

Generally, ggplot works best when you supply all the data in a single data.frame file. At least one geometry type data file.

+7
source

The only good way to do this is to rearrange your data according to the needs of the ggplot function. However, if you want to do it all right, you can. You just need to change the data manually, for example:

 ggplot(data=data.frame(value=c(d$A, d$B), variable=c(rep("A",10),rep("B",10))), aes(x=c(1:10,1:10), y=value, fill=variable))+geom_bar(stat="identity", position="dodge") 

Here I created a new data array from the old one and assigned the corresponding variable names (this is what the reshape2 package does with the melt function). Then I manually set the x values ​​to 1:10 for "A" and 1:10 for "B" so that the bars are displayed next to each other, and not everything is ok from 1:20. I added the argument "fill" to change the colors of the columns to represent "A" or "B".

+4
source

All Articles