分组条形图R.

时间:2015-09-30 14:17:39

标签: 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

我做错了什么?

2 个答案:

答案 0 :(得分: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方法的优势在于每个条形图都有自己的标签,您可以使用离散色标(如Brewer)来区分清晰度。

使用group方法,着色将反映相对值,这可能是合乎需要的,但如果bikes有更多值,可能会使得图表难以阅读,因为比较相邻Vehicles 1}}列将涉及比较细微的渐变。如果我们使用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

答案 1 :(得分: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 = Vehicles,y = TotalCost))+ geom_bar(aes(fill = as.factor(Bikes)),stat =" identity",position ="躲闪&#34)

enter image description here