ggplot

2016-05-15 48 views
3

我從這個答案question重新創建了這個情節。但是我想知道如何用平滑的圖形重疊或替換條形圖,即將X軸上的點鏈接在一起。如果他們正在更換酒吧,那麼用顏色填充它會很好。我試圖玩geom_smooth,但我不能得到它做我想要的和幫助,將不勝感激。我正在討論的問題的陰謀和代碼如下。ggplot

set.seed(1) 
df0 <- data.frame(Age = factor(rep(x = 1:10, times = 2)), 
        Gender = rep(x = c("Female", "Male"), each = 10), 
        Population = sample(x = 1:100, size = 20)) 

head(df0) 
# Age Gender Population 
# 1 1 Female   27 
# 2 2 Female   37 
# 3 3 Female   57 
# 4 4 Female   89 
# 5 5 Female   20 
# 6 6 Female   86 

library("ggplot2") 
ggplot(data = df0, aes(x = Age, y = Population, fill = Gender)) + 
    geom_bar(data = subset(df0, Gender=="Female"), 
      stat = "identity") + 
    geom_bar(data = subset(df0, Gender=="Male"), 
      stat = "identity", 
      position = "identity", 
      mapping = aes(y = -Population)) + 
    scale_y_continuous(labels = abs) + 
    coord_flip() 

Simple pyramid plot

回答

0

不知道你面臨的問題geom_smooth,我只能在它爲什麼沒有工作猜測。也許這與您將Age設置爲數據框中的一個因素有關?

我轉換時代到數字&以下工作對我來說:

df1 <- df0 %>% mutate(Age = as.numeric(as.character(Age))) 
ggplot(df1, 
     aes(x = Age, y = Population, fill = Gender, colour = Gender)) + 
    geom_bar(data = subset(df1, Gender=="Female"), alpha = 0.5, 
      stat = "identity") + 
    geom_bar(data = subset(df1, Gender=="Male"), alpha = 0.5, 
      stat = "identity", 
      position = "identity", 
      mapping = aes(y = -Population)) + 
    geom_smooth(data = subset(df1, Gender=="Female"), se = F) + 
    geom_smooth(data = subset(df1, Gender=="Male"), se = F, 
       mapping = aes(y=-Population)) + 
    scale_y_continuous(labels = abs) + 
    coord_flip() 

Resulting chart (smoothed lines overlaid on bars)