在R中绘制条形图

时间:2015-11-25 22:47:31

标签: r ggplot2

以下是数据快照: enter image description here

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 个答案:

答案 0 :(得分: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轴标签的顺序来自"之前"到"在"之后,您可以将此行:scale_x_discrete(limits = c("Before", "After"))添加到ggplot函数的末尾

答案 1 :(得分: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)

答案 2 :(得分: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)