2015-09-30 134 views
1

我有这个数据帧:分组条形图,[R

TotalCost Vehicles Bikes 
    92  1  2 
    92  1  3 
    96  1  6 
    93  2  2 
    93  2  3 
    95  2  6 
    108  3  2 
    108  3  3 
    108  3  6 

我想与填充“自行车”参数栏绘制,但这个命令:

ggplot(data, aes(Vehicles, TotalCost)) + geom_bar(aes(fill = Bikes), position = "dodge", stat="identity") 

给我这个情节,没有任何颜色 enter image description here

我在做什么错?

回答

0
library("magrittr") 
library("reshape2") 
library("ggplot2") 

rawdata = matrix(data = strsplit(split = ",", "92,1,2,92,1,3,96,1,6,93,2,2,93,2,3,95,2,6,108,3,2,108,3,3,108,3,6") %>% unlist %>% as.numeric, 
     ncol = 3, byrow = T) 
colnames(rawdata) = c("TotalCost","Vehicles","Bikes") 
df = as.data.frame(rawdata, stringsAsFactors = F) 

如果你的 “自行车” 的数据是连续的,那么你可以寻找以下:

ggplot(df, aes(x = Vehicles, y = TotalCost)) + geom_bar(aes(fill = Bikes), stat="identity") 

enter image description here

如果自行车”被更多不同的类别,那么以下可能是它:

ggplot(DF,AES(X =车辆,Y = TOTALCOST))+ geom_bar(AES(填充= as.factor(自行车)),STAT = “同一性”,位置= “躲闪”)

enter image description here

0

发生这种情况是因为您无法基于数字量躲避,因为它是连续的。如果你指定fill=factor(Bikes)它会做正确的事情;否则ggplot不知道如何“闪避”连续值。

或者,您也可以通过添加group=Bikes到美学的主情节或geom_bar明确指定分组,:

ggplot(df, aes(x=Vehicles, y=TotalCost)) + 
    geom_bar(aes(fill=Bikes, group=Bikes), position="dodge", stat="identity") 

factor方法的优点是,每个酒吧都有自己的标签,你可以使用离散色阶(如布鲁尔)来使分化清晰。

随着group方法中,着色将反映的相对值,这可能是可取的,但也可以使积硬如果存在用于bikes多个值来读取,由于比较相邻Vehicles列将涉及比较微妙灰度。如果我们在108, 3, 7附加另一行,则很难比较23分组。

ggplot(rbind(df, c(108, 3, 7)), aes(x=Vehicles, y=TotalCost)) + 
    geom_bar(aes(fill=Bikes, group=Bikes), position="dodge", stat="identity") 

enter image description here

+0

那么我该如何绘制数据框?或者我如何更改数据框以绘制分组栏? – slash89mf