Ggplot graphic chart with two data frames

What I'm trying to do is to create a "biased" histogram using gglot from two different data frames

Unfortunately, geom_bar does not see that the previous data has been added, so it shows it at the top, I tried playing with the position and width, but it seems that this does not change anything because it has one bar for each category.

The code below creates data that incorrectly displays data (bars are on top of each other) and then calculates them correctly using a workaround to bind the data.

 library("ggplot2") x<-data.frame(dat=rep(seq(1,4),3),let=rep("X")) y<-data.frame(dat=rep(seq(1,4),4),let=rep("y")) xy<-rbind(x,y) #what I would like to use with two different data frames ggplot(NULL,aes(dat))+ geom_bar(data=y,fill="red",width=0.1,position = "dodge")+ geom_bar(data=x,fill="blue",width=0.1,position = "dodge") #what I would like to see only without binding dfs ggplot(xy,aes(dat,fill=let))+geom_bar(position="dodge") 

I use ggplot to be persistent with other graphs that use only one block of data.

+7
r ggplot2
source share
1 answer
 ggplot(mapping=aes(x=dat))+ geom_bar(data=y, aes(x=dat-0.1), fill="red", binwidth=0.1)+ geom_bar(data=x, fill="blue", binwidth=0.1) 

The key here is that you move the data the same amount as one binwidth , and binwidth less than the interval between groups. Binning is performed on the data after the offset, so this affects the bin in which the data appears. In addition, without explicitly determining binwidth , how wide the cells depend on the range of the graph (therefore, it changes when xlim was diverse and worked β€œbeautifully” for round values).

enter image description here

+6
source share

All Articles