2014-03-04 52 views
0

我有简单的数据框DF(4行X 2列)...我想要为每个行值绘制一个图表(条形图)单独的图。因此,我可以相邻(在一个图形行中)获得3条柱状图,最后一个图形出现在一个新行中(延伸到整行)。我不知道为什么“计数”轴的范围是从0-1,我无法找出问题。此外,我尝试用geom_text显示在栏顶部的值,并将它似乎不工作....来自dput命令ggplot2:在一行中有3个柱状图数字,在第二行中有一个柱状图

我的数据:

structure(list(Test = structure(1:4, .Label = c("Source A", "Subject B", 
"Level C", "General rate"), class = "factor", scores = structure(c(4L, 
3L, 1L, 2L), .Dim = 4L, .Dimnames = list(c("General rate", "Level C", 
"Source A", "Subject B")))), Percentage = c(6.5, 29.1, 58.34, 
95.10)), .Names = c("Test", "Percentage"), row.names = c(NA, 
-4L), class = "data.frame") 

我的代码:

ggplot(DF, aes(Percentage)) + geom_bar(fill="gray") + 
facet_wrap(~ Test)+ 
scale_fill_manual(values = c("gray80", 
          "gray70", 
          "gray60", 
          "gray20")) 

我不得不手动填充颜色,因为某些原因scale_colour_grey(start = 0, end = .9) or scale_fill_grey(),也不和我一起工作.... enter image description here

我肯定还有很多其他很好的代表性的数据,并且完全开放给我们提出建议和新意见!

+0

原因代码为什么'scale_colour_grey(开始= 0,结束= 0.9)'和'scale_fill_grey()'不工作是你必须把'补=“灰色“'部分在ggplot-code的'aes'部分。以我的答案为例。 – Jaap

回答

1

尝试此

ggplot(DF, aes(y=Percentage, x= Test)) +geom_bar(stat="identity")+facet_wrap(~Test,scales="free_x") 

free_x,是给你在x轴的自由规模。 至于你想要什么,你将需要创建两个不同的情节,然后将其与grid.arrange结合。 因此,不具有'普通费率'且仅具有'综合费率'的数据集的子集, 创建两个图并合并它们。下面

df.1 <-subset(DF, Test!="General rate") 
df.2 <-subset(DF, Test=="General rate") 
#plot top 
plot.top <-ggplot(df.1, aes(y=Percentage, x= Test)) +geom_bar(stat="identity")+facet_wrap(~Test,scales="free_x") 
#plot bottom 
plot.bottom <-ggplot(df.2, aes(y=Percentage, x= Test)) +geom_bar(stat="identity")+facet_wrap(~Test,scales="free_x") 
library(gridExtra) 
#Loading required package: grid 
grid.arrange(plot.top, plot.bottom) 

The Result with grid.arrange

2

为什么要使用facet's?在这种情况下,我认为只制作一个barplot会更好,因此您可以更好地比较不同的群体。

示例代码:

ggplot(df, aes(x=Test, y=Percentage, fill=Test)) + 
    geom_bar() 

其结果是: enter image description here

+0

和是的,除非有一个非常具体的理由你想要的情节描述,我会去这个,因为它更容易比较所有在一个情节。当你有更多的分组级别时,分面更容易 – infominer

+0

你是对的,但我需要在一个单独的图中显示一般速率,计算方式不同......感谢评论@Jaap! – SimpleNEasy