2016-03-16 48 views
-1

我需要關於ggplot2的R圖形問題的幫助。 讓我們舉一個例子:帶有幾個x變量的ggplot2圖形?

date <- c("oct", "dec") 

min.national <- c(17, 20) 
min.international <- c(11, 12) 
min.roaming <- c(5, 7) 

mb.national <- c(115, 150) 
mb.international <- c(72, 75) 
mb.roaming <- c(30, 40) 

df <- data.frame(min.national, min.international, min.roaming, mb.national, mb.international, mb.roaming) 

我想是有兩個圖形一個用於分鐘和一個用於兆副業。並在同一圖形上獲得三個變量(例如國內,國際和漫遊的分鐘數)的條形圖fill = date? 你明白嗎? 感謝

+0

什麼是不明確的是你已經嘗試過自己。 – mtoto

+0

抱歉,你的意思是? –

+0

對不起,但我試過了,這是一件很難做的事情,我可以告訴你我在R或基於Excel的基本圖形? –

回答

2

我很欣賞這裏可能有一個語言的挑戰,它聽起來就像你剛開始接觸GGPLOT2所以不知道如何讓這個開始,所以我希望你找到這個有用的。

分開處理分鐘和mb是有意義的;他們是不同的單位。所以我只會用分鐘作爲例子。正確的方法和tidyr庫很容易理解你想要實現的目標。

library(tidyr) 
library(ggplot2) 
#first get your data in a data frame 
min.df <- data.frame(national = min.national, international = min.international, roaming = min.roaming, month = date) 
#now use the tidyr function to create a long data frame, you should recognize that this gives you a data structure readily suited to what you want to plot 
min.df.long <- gather(min.df, "region", "minutes", 1:3) 
ggplot(min.df.long) + geom_bar(aes(x = region, y = minutes, fill = month), stat = "identity") 

enter image description here

如果你想在幾個月並排,我明白你的問題,那麼你可以做:

ggplot(min.df.long) + geom_bar(aes(x = region, y = minutes, fill = factor(month, levels = c("oct", "dec"))), position = "dodge", stat = "identity") + labs(fill = "month") 

的關鍵參數是位置關鍵字,其餘爲只是爲了讓它更整潔。 enter image description here

+0

非常感謝你,還有一個問題,如何使酒吧並排和按日期?我認爲這很容易理解 (PS:我不是新的ggplot,但我有一些問題,使用tidyr和重塑...) –

+1

請參閱編輯的答案,我認爲,隨你問;這是一個簡單的geom_bar位置選項。 – doctorG

2
df <- data.frame(date, min.national, min.international, min.roaming, mb.national, mb.international, mb.roaming) 

df.stk <- tidyr::separate(melt(df), col="variable", into=c("min_byte", "type"), sep="\\.") 

plt <- ggplot(df.stk, aes(type, value, fill = date)) + 
     geom_bar(stat = "identity") + 
     facet_grid(.~min_byte) 
print(plt) 

enter image description here

+0

非常感謝! –

+0

歡迎您,如果這回答了您的問題,請將其標記爲已回答。 – TheRimalaya

相關問題