2017-10-04 525 views
0

我認爲我需要使用熔化函數,但我不知道該怎麼做?下面的示例數據,代碼和結果圖。基本上,「cnt」列由每行「註冊」加上「隨便」組成。我想顯示「註冊」與總「隨便總」每月,而不是整體的總‘CNT’使用ggplot2並排繪製兩個變量條形圖

example data

#Bar Chart 
bar <- ggplot(data=subset(bikesharedailydata, !is.na(mnth)), aes(x=mnth, y=cnt)) + 
    geom_bar(stat="identity", position="dodge") + 
    coord_flip() + 
    labs(title="My Bar Chart", subtitle = "Total Renters per Month", caption = "Caption", x = "Month", y = "Total Renters") + 
    mychartattributes 

enter image description here

+0

我使你的第二圖像公衆,但不是你的第一個與數據的Excel的屏幕截圖。嘗試提取數據的重要部分而不添加任何列,並使用dput()提供數據集。 –

+0

Ooops,@ r2evans發佈了兩個.... –

+0

對不起,快速編輯...我認爲你不應該發佈數據圖像。 – r2evans

回答

0

要‘融化’你的數據使用reshape2::melt

library(ggplot2) 
library(reshape2) 

# Subset your data 
d <- subset(bikesharedailydata, !is.na(mnth)) 
# Select columns that you will plot 
d <- d[, c("mnth", "registered", "casual")] 
# Melt according to month 
d <- melt(d, "mnth") 

# Set fill by variable (registered or casual) 
ggplot(d, aes(mnth, value, fill = variable)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    coord_flip() + 
    labs(title="My Bar Chart", subtitle = "Total Renters per Month", 
     caption = "Caption", 
     x = "Month", y = "Total Renters") 
0

使用tidyr和dplyr:

set.seed(1000) 
library(dplyr) 
library(tidyr) 
library(ggplot2) 

bikesharedailydata <- data.frame(month = month.abb, registered = rpois(n = 12, lambda = 2), casual =rpois(12, lambda = 1)) 


bikesharedailydata %>% gather(key="type", value = "count", -month) %>% 
    ggplot(aes(x=month, y=count, fill = type))+geom_bar(stat = "identity", position = "dodge") 

enter image description here

相關問題