2017-07-20 58 views
2

使用ggplot創建geom_bar兩個表時出現問題。 我有兩個表:如何使用ggplot創建兩個表的geom_bar

1) 
    characteristic men_weekly_earnings 
1  16 to 24 years    493 
2  16 to 19 years    392 
3  20 to 24 years    507 
4  25 to 34 years    755 
5  35 to 44 years    964 
6  45 to 54 years    1011 
7  55 to 64 years    1021 
8 65 years and older    942 


2) 
    characteristic women_weekly_earnings 
1  16 to 24 years     451 
2  16 to 19 years     357 
3  20 to 24 years     468 
4  25 to 34 years     679 
5  35 to 44 years     781 
6  45 to 54 years     780 
7  55 to 64 years     780 
8 65 years and older     740 

每個表由不同的年齡有周薪數據。 我的目標是將兩個表格合併爲一個爲 like this

x軸是特徵列,y軸是weekly_earnings列。

現在我試過這個代碼(男表,它不工作

ggplot(data = men) + geom_col(mapping = aes(x= characteristic,y= men_weekly_erning)) 

我現在該怎麼辦?

謝謝。

+0

什麼是錯誤您收到? – mannym

回答

2

歡迎堆棧溢出!

我認爲你最好的選擇是將兩個數據集疊在一起然後繪製它們。例如:

df_all <- rbind(cbind(setNames(men_df, c("characteristic", "weekly_earnings")), source = "men"), 
       cbind(setNames(women_df, c("characteristic", "weekly_earnings")), source = "women")) 


ggplot(data = df_all) + 
    geom_col(mapping = aes(x= source, y = weekly_earnings, fill = characteristic), position = position_dodge()) 

enter image description here

注意如何當我創建df_all我添加一列指定源不同的地方的數據來自(無論是「男」 /「女」)。這使您可以在ggplot呼叫中分解出來。還要注意,在堆疊之前,我必須使兩個數據集之間的列名一致。我爲此使用了setNames命令。


數據:

women_df <- structure(list(characteristic = c("16 to 24 years", "16 to 19 years", 
"20 to 24 years", "25 to 34 years", "35 to 44 years", "45 to 54 years", 
"55 to 64 years", "65 years and older"), women_weekly_earnings = c(451L, 
357L, 468L, 679L, 781L, 780L, 780L, 740L)), .Names = c("characteristic", 
"women_weekly_earnings"), row.names = c(NA, -8L), class = "data.frame") 

men_df <- structure(list(characteristic = c("16 to 24 years", "16 to 19 years", 
"20 to 24 years", "25 to 34 years", "35 to 44 years", "45 to 54 years", 
"55 to 64 years", "65 years and older"), men_weekly_earnings = c(493L, 
392L, 507L, 755L, 964L, 1011L, 1021L, 942L)), .Names = c("characteristic", 
"men_weekly_earnings"), row.names = c(NA, -8L), class = "data.frame") 
+0

謝謝Mike H.它的作品像魔術一樣!你是男人! –