2015-07-20 31 views
0

我想使用ggplot2生成的直方圖的背景着色。我想要的背景爲look like the one in the answer here使用帶geom_histogram的geom_rect

這是我的代碼:

dates <- seq(from = as.Date("2015/1/1"), to = as.Date("2015/12/31"), "day") 

library(lubridate) 
day <- yday(dates) 
month <- month(dates) 

df <- data.frame(day, month) 

library(dplyr) 
df %>% 
sample_n(50) -> 
df 

library(ggplot2) 
ggplot(df, aes(day)) + geom_histogram() + 
    scale_x_continuous(breaks = seq(0, 365, 10), limits = c(0, 365)) + 
    theme_bw() 

將會產生這樣的情節:

enter image description here

而這正是我想,這不工作:

ggplot(df, aes(day)) + geom_histogram() + 
    geom_rect(xmin = day, xmax = day, ymin = -Inf, ymax = Inf, fill = month) + 
    scale_x_continuous(breaks = seq(0, 365, 10), limits = c(0, 365)) + 
    theme_bw() 
+0

答案是很清楚的,你需要做什麼。它的哪一部分很難理解? –

+0

你看過你的問題的其他答案嗎? http://stackoverflow.com/questions/31510796/shade-background-of-ggplot-according-to-month/31511456#31511456 – Heroka

+0

@RomanLuštrik如果你看鏈接答案中的'rects','xstart'和' geom_rect的xend參數都有自己的變量。但是在我創建的'df'中,我只有一個變量'day',它被'geom_histogram'轉換爲bin,所以不清楚'xmin'和'xmax'應該是什麼值。 – luciano

回答

2

您嘗試繪製採樣數據中的矩形,這將不起作用,因爲數據是失蹤。要繪製矩形,您需要指定每個月的開始和結束日期,最好通過爲此創建額外的數據集來實現。

該數據幀,創建如下:

library(dplyr) 
month_df <- df %>% 
      group_by(month) %>% 
      summarize(start=min(day),end=max(day) + 1) %>% 
      mutate(month=as.factor(month)) 
# correct the last day of the year 
month_df[12,"end"] <- month_df[12,"end"] - 1 

您在更換由50個樣本df之前做的是很重要的。最後一行有點不愉快:爲了避免矩形之間的空白,我在本月的最後一天添加一個。這不應該在最後一天完成。它的工作原理,但也許你找到了一個更簡潔的解決方案......

month_df前幾行應該是

month start end 
1  1  1 32 
2  2 32 60 
3  3 60 91 

現在,該地塊可以通過

ggplot(df) + 
    geom_rect(data=month_df,aes(xmin = start, xmax = end, fill = month), 
      ymin = -Inf, ymax = Inf) + 
    geom_histogram(aes(day)) + 
    scale_x_continuous(breaks = seq(0, 365, 10), limits = c(0, 365)) + 
    theme_bw() 

一些言論被創建: *重要的是geom_rect()之前geom_histogram()爲了在背景中有矩形。 *我從ggplot()geom_histogram()中刪除了aes(day),因爲它僅在那裏使用。否則,它會混淆geom_rect(),你會得到一個錯誤。 * ymin=-Infymax=Inf不是來自數據的意見映射,因爲它們實際上設置爲常量。所以沒有必要在aes()裏面有這些。不過,如果你把它們放在aes()之內,沒什麼不好的。

情節我得到的是以下幾點:

enter image description here