2016-03-05 71 views
1

我每年都得到關於頻率的數據。我用ggplot2對這些數據(x - 年; y - 頻率)進行了barplot。現在我想通過爲1980年以下的所有酒吧用紅色和所有酒吧等於或高於1980年用綠色着色來分開barplot圖。我該如何做到這一點 - 下面是我的MWE試圖用scale_fill_manual設置這些邊界,因爲我沒有正確地做到這一點,所以無法正常工作。ggplot2 - 用兩種顏色分開barplot

數據

dput(allePubs2) 
structure(list(Jahr = 1922:2015, Publikationen = c(1L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 
0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 2L, 0L, 0L, 0L, 1L, 0L, 1L, 4L, 
2L, 3L, 2L, 2L, 4L, 1L, 4L, 1L, 3L, 6L, 1L, 2L, 2L, 3L, 1L, 2L, 
5L, 5L, 5L, 5L, 5L, 5L, 5L, 12L, 4L, 5L, 14L, 9L, 6L, 5L, 7L, 
5L, 6L, 4L, 7L, 3L, 7L, 6L, 7L, 8L, 6L, 4L, 14L)), .Names = c("Jahr", 
"Publikationen"), row.names = c(NA, -94L), class = "data.frame") 

MWE嘗試

cutoff80 <- 
    ggplot(data=allePubs2, aes(x=Jahr, y=Publikationen)) + 
    geom_bar(stat="identity", width = 0.5)+ 
    scale_y_continuous(name="Anzahl Publikationen", breaks = 0:14, limits = c(0, 15))+ 
    scale_x_continuous(name="Jahr", breaks = c(1920, 1925, 1930, 1935, 1940, 1945, 1950, 1955, 1960, 1965, 1970, 1975, 
              1980, 1985, 1990, 1995, 2000, 2005, 2010, 2015), 
        limits = c(1920, 2016))+ 
    ggtitle("Cut-Off bei 1980")+ 
    theme_hc() + 
    geom_vline(xintercept = 1979.5)+ 
    scale_fill_manual(breaks = c("1922", "1979","1980","2016"), 
        values=c("red", "red", "green", "green")) 
cutoff80 
+0

歡迎來到Stack Overflow!您的問題不包含[可重現的示例](http://stackoverflow.com/q/5963269/4303162)。因此很難理解你的問題並給你一個合適的答案。請提供您的數據(例如使用'dput()')或使用R中的示例數據集之一。另外,添加將您的問題重現到您的文章所需的最小代碼。 – Stibu

+0

感謝您的反饋意見。我添加了數據和MWE。希望它的幫助和正確? – Jens

+0

感謝您添加數據和您的代碼!這正是爲了讓您的問題能夠負責所需要的。一個小小的抱怨依然存在:將您的示例放在最小範圍內是有用的,因爲您忽略了與手頭問題無關的任何事情。我認爲你應該忽略'theme_hc()',因爲它似乎不是一個標準功能,並且與你的問題沒有關係。但總的來說,你在改善問題方面做得很好。 – Stibu

回答

1

您可以添加一個變量可以用來控制條的顏色數據幀:

allePubs2$before1980 <- factor(allePubs2$Jahr < 1980, 
          levels = c(TRUE, FALSE), 
          labels = c("vor 1980", "nach 1980")) 

這裏,我使用factor將邏輯變量轉換爲因子。標籤稍後將用於圖例中,因此在此適當選擇它們非常重要。

現在你可以映射before1980到多的顏色像你映射Jahr的x座標:

library(ggplot2) 
ggplot(data=allePubs2, aes(x=Jahr, y=Publikationen, fill = before1980)) + 
    geom_bar(stat="identity", width = 0.5)+ 
    scale_y_continuous(name="Anzahl Publikationen", breaks = 0:14, limits = c(0, 15))+ 
    scale_x_continuous(name="Jahr", breaks = seq(1920, 2015, by = 5), 
        limits = c(1920, 2016))+ 
    ggtitle("Cut-Off bei 1980")+ 
    geom_vline(xintercept = 1979.5)+ 
    scale_fill_manual(name = "", values = c("vor 1980" = "red", "nach 1980" = "green")) 

enter image description here

我還定義了一個手動的規模,使得確保顏色是你希望他們擁有的方式。請注意,如何將某個值鏈接到顏色爲"vor 1980" = "red"。參數name可用於設置圖例的標題,並按照您的要求將其設置爲空。

我也使用seq簡化了scale_y_continuous()的中斷,並刪除了theme_hc(),因爲我不知道該函數來自哪裏。

+0

非常智能的解決方案!我很喜歡。最後一件事:我怎樣才能以下列方式改變傳說:去掉1980年之前的「1980年」之後的紅色標記和1980年之後的「綠色標記」之後設置「1980年前」? – Jens

+0

超級!謝謝! – Jens