带两个数据帧的ggplot条形图 [英] ggplot bar chart with two dataframes
问题描述
我试图做的是使用来自两个不同数据框的gglot创建一个闪避条形图
不幸的是 geom_bar
没有看到之前添加的数据,所以它将它绘制在顶部,我试着玩过位置和宽度,但它似乎没有改变任何东西,可能是因为它是每个类别一个酒吧。
下面的代码会创建数据错误地绘制数据(条形在另一个之上),然后使用将数据框绑定在一起的解决方法正确绘制数据。 ($ g $ p
$ b $ ,4),3),let = rep(X))
y <-data.frame(dat = rep(seq(1,4),4),let = rep(y))
xy <-rbind(x,y)
我想用于两个不同的数据框
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 = 闪避)
#what我wou ld喜欢只看到没有绑定dfs
ggplot(xy,aes(dat,fill = let))+ geom_bar(position =dodge)
我使用ggplot与其他只使用单个数据帧的图形保持不变。
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)
这里的关键是您将数据移动的数量与 What I am trying to do is create a "dodged" bar chart using gglot from two different dataframes Unfortunately The code below creates the data plots the data incorrectly (bars are on top of one another) and then plots it correctly using a workaround of binding the dataframes together. I'm using ggplot to be constant with other plots that use only a single dataframe. The key here is that you are shifting the data by the same amount as one 这篇关于带两个数据帧的ggplot条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! binwidth
和 binwidth $ c $相同c>小于组之间的间距。在移位后对数据进行分箱,以便影响数据出现的位置。另外,如果未明确设置
binwidth
,则分箱的宽度取决于范围(这就是为什么当 xlim
变化并且对于圆形值很好地工作时它是变化的)。
geom_bar
doesn't see the previous data added so it plots it right over top, I've tried playing with position and width but it doesn't seem to change anything probably due to the fact that it is one bar per category.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")
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)
binwidth
and that binwidth
is less than the spacing between groups. The binning is done on the data after shifting, so that affects which bin the data appears in. Also, without setting the binwidth
explicitly, how wide the bins are depend on the range of the plot (which is why it varies when xlim
was varied and worked "nicely" for round values).