2014-07-26 31 views
0

我正在尝试制作一个分组条形图...进行了一些修改。条形图+线条图与GGPlot一张图

我的图表有四个“列”:季度,人员,百分比,总计百分比。我的数据示例如下所示:

|人员| Quarter |百分比|总的百分比|

| -------- | --------- | ------------ | ------------- ----- |

| A | 1 | 40%| 50%|

| A | 2 | 45%| 50%|

| A | 3 | 55%| 50%|

| A | 4 | 60%| 50%|

| B | 1 | 35%| 42%|

等等。

我已经使用此代码成功地使我的条形图:

ggplot(data=point3, aes(x=Person, y=Percentage, fill=Quarter)) + 
+  geom_bar(colour="black", stat="identity", position=position_dodge(), size=.3)      
+  scale_fill_hue(name="Quarter") 
+  xlab(" ") + ylab("Percentage") 
+  theme_bw() 

不过,我想改变一些东西。首先,我想摆脱x轴。每个人有四个酒吧,我想知道如何让每个人都有更多的空间。我遇到了麻烦,因为X轴不包含任何类型的数字。有谁知道如何做到这一点?

其次,我想为每个人代表他们的总比例添加一条垂直线。通过这种方式,观众可以很容易地看到这个人在他们的年平均水平下执行了哪个季度,以及他们在哪个季度执行过多。我曾与此使用

geom_point(data=point3, aes(x=Person, y=Total Percentage)) 

在前面的代码结束一点点成功,但是这只是增加了第二和第三条(中间)之间的点。我做了一个mock up of this using a grouped bar chart我通过Google找到。这个只有3个酒吧,但也许你可以明白。这次我遇到的一些问题是,虽然它们的尺寸相同,但条形图的y轴为“性能”,而线条的y轴为“总体性能”。 R似乎并不喜欢这样。另外,整个x轴不是数字。

我使用了ggplot2,因为我不知道还有什么用,但如果你知道任何技术/软件包来完成这项工作,我很乐意改变这一点。我也知道我可能需要重塑我的数据,这也很酷。

非常感谢。

回答

0

我不得不添加到您的示例数据,使其更“完整”,并使R友好的列名称。

point3<-structure(list(Person = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), 
.Label = c("A", "B"), class = "factor"), 
Quarter = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), Percentage = c(40L, 
45L, 55L, 60L, 35L, 40L, 60L, 25L), TotalPercentage = c(50L, 50L, 50L, 50L, 
42L, 42L, 42L, 42L)), .Names = c("Person", "Quarter", "Percentage", 
"TotalPercentage"), class = "data.frame", row.names = c(NA, -8L)) 

然后你就可以控制与width=position_dodge(width=)的间距。然后添加栏,我将缩小的数据框传递到geom_segment,并将这些因子转换为数字,以便能够在x轴上展开。

ggplot(data=point3, aes(x=Person, y=Percentage, fill=factor(Quarter))) + 
    geom_bar(colour="black", stat="identity", 
     position=position_dodge(width=.80), width=.5) + 
    geom_segment(data=unique(point3[,c("Person","TotalPercentage")]), 
     aes(x=as.numeric(Person)-.4, xend=as.numeric(Person)+.4, 
     y=TotalPercentage, yend=TotalPercentage), 
     inherit.aes=F, size=1.2) + 
    scale_fill_hue(name="Quarter") + 
    xlab(" ") + ylab("Percentage") + 
    theme_bw() 

这最终看起来像

enter image description here

+0

哇,你是钉。我想弄清楚你做了什么。我的主要问题是为什么每个数据输入结尾的“L”?我有点迷失在那里。但是,严重的是,这真棒。谢谢。 – tsdryt

+0

我上面发布的示例数据是从'dput'输出的。这就是R如何喜欢编码整数文字。如果没有L的话,它会工作的很好 – MrFlick

1

另一种方式来做到这一点是使用geom_errorbar:

ggplot(data=point3, aes(x=Person, y=Percentage, fill=factor(Quarter))) + 
    geom_bar(colour="black", stat="identity", position=position_dodge(width=0.9), width=.8) + 
    geom_errorbar(aes(y=TotalPercentage, ymax=TotalPercentage, ymin=TotalPercentage), linetype="solid",size=1) + 
    scale_fill_hue(name="Quarter") + 
    xlab(" ") + ylab("Percentage") + 
    theme_bw() 

enter image description here