簡體   English   中英

結合使用geom_rect和geom_histogram

[英]Using geom_rect with geom_histogram

我想為使用ggplot2生成的直方圖的背景ggplot2 我希望背景看起來像這里的答案

這是我的代碼:

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()

產生此圖:

在此處輸入圖片說明

這是我嘗試過的,不起作用:

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()

您嘗試從采樣數據中繪制矩形,但由於數據丟失,將無法正常工作。 要繪制矩形,您需要指定每個月的開始和結束日期,最好為此創建一個額外的數據集來實現。

我創建的這個數據框如下:

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

請務必執行此操作, 然后 df 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()刪除了aes(day)並放入了geom_histogram()因為它僅在此處使用。 否則,它將混淆geom_rect()並且您將得到一個錯誤。 * ymin=-Infymax=Inf不是來自數據的美學映射,因為它們實際上已設置為常數。 因此,不需要在aes()包含這些內容。 但是,如果將它們保留在aes() ,則不會發生任何不良情況。

我得到的情節如下:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM