ggplot2 - 堆叠/遮挡条形图 [英] ggplot2 - Stacking / dodging bar chart

查看:510
本文介绍了ggplot2 - 堆叠/遮挡条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在制作条形图方面存在问题,其中y轴不计数,但是来自变量的值。

我使用 stat = identity ,这对一个变量很好。但是如果我有两个变量并且想要创建一个堆栈/躲避条形图?



这里有一些模拟数据:

  foo < -  data.frame(case = c('A','B','C'),var1 = rnorm(3),var2 = rnorm(3 ))

所以我在x轴上的三种情况是A,B和C.我想绘制var1和var2的值为条。感谢! 解决方案首先,更改您的示例数据。在制作数据框时,您不需要 cbind(),因为在这种情况下,您可以将所有列设置为因子。

<$ (data_frame)(case = c('A','B','C'),var1 = rnorm(3),var2 = rnorm(3))

要使用barplot的两个变量最简单的方法是将数据从宽格式融合到长格式。 p>

  library(reshape2)
foo.long< -melt(foo)
foo.long
案例变量值
1 A var1 0.7150827
2 B var1 -0.5279363

现在对于填充,使用作为y值并使用变量 stat =identity position =dodge将确保实际值被绘制并且条形图被锁定。 / p>

  ggplot(foo.long,aes(case,value,fill = variable))+ 
geom_bar(position = dodge,stat =identity)


I am having issues with making barchart in which the y axis is not count, but value from variables.

I use stat=identity, which is fine for one variable. But what if I have two variables and want to create a stacking / dodging barchart?

I have some mock data here:

foo <- data.frame(case=c('A','B','C'), var1=rnorm(3), var2=rnorm(3))

So my three cases on x-axis are A, B, and C. I want to plot the values of var1 and var2 as bars. Thanks!

解决方案

First, changed your sample data. When making data frame you don't need cbind() because in this case you make all columns as factors.

foo <- data.frame(case=c('A','B','C'), var1=rnorm(3), var2=rnorm(3))

To use two variables for barplot easiest way would be to melt the data from wide to long format.

library(reshape2)
foo.long<-melt(foo)
foo.long
  case variable      value
1    A     var1  0.7150827
2    B     var1 -0.5279363

Now use value as y values and variable for the fill. stat="identity" and position="dodge" will ensure that actual values are plotted and bars are dogged.

ggplot(foo.long, aes(case,value,fill=variable))+
      geom_bar(position="dodge",stat="identity")

这篇关于ggplot2 - 堆叠/遮挡条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆