簡體   English   中英

在R中繪制條形圖

[英]Plotting a bar graph in R

這是數據快照: 在此處輸入圖片說明

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()

這並沒有給我想要的結果。 請幫忙!!

所以...類似:

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)

會產生:

在此處輸入圖片說明


編輯:

為了更加美觀,例如使x軸標簽的順序從“之前”到“之后”,您可以添加以下行: scale_x_discrete(limits = c("Before", "After"))到最后ggplot函數

您的數據格式不正確,無法與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)

您必須融合您的數據:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM