[英]ggplot2 - How to plot length of time using geom_bar?
我試圖通過顯示多個地區的作物種植和收獲日期來顯示不同的生長季節長度。
我的最終目標是一個看起來像這樣的圖表:
這是從這個問題的答案中提取的。 請注意,日期以儒略日(一年中的某一天)為單位。
我第一次嘗試重現類似的情節是:
library(data.table)
library(ggplot2)
mydat <- "Region\tCrop\tPlanting.Begin\tPlanting.End\tHarvest.Begin\tHarvest.End\nCenter-West\tSoybean\t245\t275\t1\t92\nCenter-West\tCorn\t245\t336\t32\t153\nSouth\tSoybean\t245\t1\t1\t122\nSouth\tCorn\t183\t336\t1\t153\nSoutheast\tSoybean\t275\t336\t1\t122\nSoutheast\tCorn\t214\t336\t32\t122"
# read data as data table
mydat <- setDT(read.table(textConnection(mydat), sep = "\t", header=T))
# melt data table
m <- melt(mydat, id.vars=c("Region","Crop"), variable.name="Period", value.name="value")
# plot stacked bars
ggplot(m, aes(x=Crop, y=value, fill=Period, colour=Period)) +
geom_bar(stat="identity") +
facet_wrap(~Region, nrow=3) +
coord_flip() +
theme_bw(base_size=18) +
scale_colour_manual(values = c("Planting.Begin" = "black", "Planting.End" = "black",
"Harvest.Begin" = "black", "Harvest.End" = "black"), guide = "none")
然而,這個情節有幾個問題:
因為條形是堆疊的,所以 x 軸上的值被聚合並最終變得太高 - 超出了代表一年中某天的 1-365 比例。
我需要將Planting.Begin
和Planting.End
組合成相同的顏色,並對Harvest.Begin
和Harvest.End
做同樣的Harvest.End
。
此外,需要在Planting.Begin
和Harvest.End
之間創建一個“空白”(或完全無色的條)。
也許可以使用geom_rect
或geom_segment
來實現圖形,但我真的想堅持使用geom_bar
因為它更具可定制性(例如,它接受scale_colour_manual
以便為條形添加黑色邊框)。
有關如何創建此類圖的任何提示?
我不認為這是你可以用geom_bar
或geom_col
做的geom_col
。 更通用的方法是使用geom_rect
繪制矩形。 為此,我們需要稍微重塑數據
plotdata <- mydat %>%
dplyr::mutate(Crop = factor(Crop)) %>%
tidyr::pivot_longer(Planting.Begin:Harvest.End, names_to="period") %>%
tidyr::separate(period, c("Type","Event")) %>%
tidyr::pivot_wider(names_from=Event, values_from=value)
# Region Crop Type Begin End
# <chr> <fct> <chr> <int> <int>
# 1 Center-West Soybean Planting 245 275
# 2 Center-West Soybean Harvest 1 92
# 3 Center-West Corn Planting 245 336
# 4 Center-West Corn Harvest 32 153
# 5 South Soybean Planting 245 1
# ...
我們使用tidyr
來重塑數據,因此我們要繪制的每個矩形都有一行,並且我們還使 Crop 成為一個因素。 然后我們可以像這樣繪制它
ggplot(plotdata) +
aes(ymin=as.numeric(Crop)-.45, ymax=as.numeric(Crop)+.45, xmin=Begin, xmax=End, fill=Type) +
geom_rect(color="black") +
facet_wrap(~Region, nrow=3) +
theme_bw(base_size=18) +
scale_y_continuous(breaks=seq_along(levels(plotdata$Crop)), labels=levels(plotdata$Crop))
這里有點混亂的部分是我們對y
使用離散比例但geom_rect
更喜歡數值,因此由於現在這些值是因子,我們使用因子的數值來創建 ymin 和 ymax 位置。 然后我們需要用因子水平的名稱替換 y 軸。
如果您還想在x
軸上獲取月份名稱,您可以執行以下操作
dateticks <- seq.Date(as.Date("2020-01-01"), as.Date("2020-12-01"),by="month")
# then add this to you plot
... +
scale_x_continuous(breaks=lubridate::yday(dateticks),
labels=lubridate::month(dateticks, label=TRUE, abbr=TRUE))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.