2015-11-25 55 views
2

这里是数据的快照: enter image description hereR中绘制的柱状图

restaurant_change_sales = c(3330.443, 3122.534) 
restaurant_change_labor = c(696.592, 624.841) 
restaurant_change_POS = c(155.48, 139.27) 
rest_change = data.frame(restaurant_change_sales, restaurant_change_labor, restaurant_change_POS) 

我想为每个指示改变的列的两个杆。每个列的一个图表。

我想:

ggplot(aes(x = rest_change$restaurant_change_sales), data = rest_change) + geom_bar() 

这是不给结果我想要的方式。请帮忙!!

+3

我试图将你的数据图像复制到R,所以我可以测试你的代码,但它不起作用。你能否将它作为文字提供? – thelatemail

回答

2

您的数据格式不正确,无法与ggplot2一起使用,或者R中的任何绘图软件包。所以我们先修复你的数据,然后用ggplot2来绘制它。

library(tidyr) 
library(dplyr) 
library(ggplot2) 

# We need to differentiate between the values in the rows for them to make sense. 
rest_change$category <- c('first val', 'second val') 

# Now we use tidyr to reshape the data to the format that ggplot2 expects. 
rc2 <- rest_change %>% gather(variable, value, -category) 
rc2 

# Now we can plot it. 
# The category that we added goes along the x-axis, the values go along the y-axis. 
# We want a bar chart and the value column contains absolute values, so no summation 
# necessary, hence we use 'identity'. 
# facet_grid() gives three miniplots within the image for each of the variables. 
ggplot2(rc2, aes(x=category, y=value, facet=variable)) + 
    geom_bar(stat='identity') + 
    facet_grid(~variable) 
0

你必须融化你的数据:

library(reshape2) # or library(data.table) 
rest_change$rowN <- 1:nrow(rest_change) 
rest_change <- melt(rest_change, id.var = "rowN") 
ggplot(rest_change,aes(x = rowN, y = value)) + geom_bar(stat = "identity") + facet_wrap(~ variable) 
3

所以......是这样的:

library(ggplot2) 
library(dplyr) 
library(tidyr) 

restaurant_change_sales = c(3330.443, 3122.534) 
restaurant_change_labor = c(696.592, 624.841) 
restaurant_change_POS = c(155.48, 139.27) 
rest_change = data.frame(restaurant_change_sales, 
         restaurant_change_labor, 
         restaurant_change_POS) 

cbind(rest_change, 
     change = c("Before", "After")) %>% 
    gather(key,value,-change) %>% 
    ggplot(aes(x = change, 
      y = value)) + 
    geom_bar(stat="identity") + 
    facet_grid(~key) 

将产生:

enter image description here


编辑:

为了增加花哨的感觉,使x轴标签的顺序从“之前”变为“之后”,您可以在ggplot函数的末尾添加以下行:scale_x_discrete(limits = c("Before", "After"))