2015-11-25 54 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"))