2017-03-15 31 views
0

我想在R studio中使用ggplot並排使用兩個變量來創建條形圖。我試着按照我在網上找到的其他人的建議,但我不能得到它的工作。ggplot條形圖並排使用兩個變量

下面是我使用的數據:

x <- c(5,17,31,9,17,10,30,28,16,29,14,34) 

y <- c(1,2,3,4,5,6,7,8,9,10,11,12) 

day <- c(1,2,3,4,5,6,7,8,9,10,11,12) 

所以,我想要做的是對由x和y(側barplots x軸和側天X &ÿ被着色)對應於日期編號。

首先我是使一個數據幀:

df1 <- data.frame(x,y,day) 

,然後我嘗試:

ggplot(DF1,AES(X =天,Y = X,Y))+ geom_bar(stat =「identity」,color = x,width = 1,position =「dodge」)

但是我只是無法讓它正常工作。有關我如何實現這一目標的任何建議?

+0

後續問題:您是否希望顏色基於當天?或者是基於它們是在「x」還是「y」組中的顏色? – TaylorV

回答

3

你有正確的想法,我認爲melt()功能從reshape2包是你正在尋找。

library(ggplot2) 
library(reshape2) 

x <- c(5,17,31,9,17,10,30,28,16,29,14,34) 
y <- c(1,2,3,4,5,6,7,8,9,10,11,12) 
day <- c(1,2,3,4,5,6,7,8,9,10,11,12) 


df1 <- data.frame(x, y, day) 
df2 <- melt(df1, id.vars='day') 
head(df2) 

ggplot(df2, aes(x=day, y=value, fill=variable)) + 
    geom_bar(stat='identity', position='dodge') 

enter image description here

+0

完美,正是我想要的......感謝您的幫助 – Electrino

0

或者你可以使用facet_wrap產生兩個地塊:

ggplot(data = df2, aes(x = day, y = value, fill = day)) + geom_bar(stat = "identity") + facet_wrap(~ variable) + scale_x_continuous(breaks=seq(1,12,2)) 

library("ggplot2") 
    library("reshape") 
    x <- c(5,17,31,9,17,10,30,28,16,29,14,34) 
    y <- c(1,2,3,4,5,6,7,8,9,10,11,12) 
    day <- c(1,2,3,4,5,6,7,8,9,10,11,12) 
    df1 <- data.frame(x,y,day) 
    df2 <- reshape::melt(df1, id = c("day")) 
    ggplot(data = df2, aes(x = day, y = value, fill = variable)) + geom_bar(stat = "identity")+ facet_wrap(~ variable) + scale_x_continuous(breaks=seq(1,12,2)) 

enter image description here 如果根據日常使用fill = day希望與顏色條

enter image description here

+0

另外值得注意的是,如果您將日期轉換爲因子 – TaylorV

+0

,那麼您可以使用'+ scale_x_continuous(中斷= seq(1,12,2))'在x軸上的整數值。 –