簡體   English   中英

如何填充/着色 ggplot2 中重疊的兩條線的區域?

[英]How to fill/shade the area of two lines that overlap in ggplot2?

ggplot2中,我試圖填充/遮蔽兩條重疊的線的區域。 每條線代表 24 小時內的一個物種,陰影區域代表物種重疊。 我已經嘗試過geom_ribbon() ,但似乎無法弄清楚 ymin 和 ymax,並且geom_polygon()似乎只在垂直和水平線之間填充時效果最好。 為簡化起見,我包含了示例數據,但問題與我的數據完全相同。

library(overlap)
library(ggplot2)

# Sample data
data(kerinci)
head(kerinci)

# Convert time to radians
timeRad <- kerinci$Time * 2 * pi

# Filter species and time
tig2 <- timeRad[kerinci$Zone == 2 & kerinci$Sps == 'tiger']
mac2 <- timeRad[kerinci$Zone == 2 & kerinci$Sps == 'macaque']

# Create density overlap plot with 'Overlap' package plot
overlapPlot(tig2, mac2, main="Zone 2")

# Create df of tig and mac density and time values
tigmac <- overlapPlot(tig2, mac2, main="Zone 2")

# Create density overlap plot in ggplot2
p <- ggplot() +
  geom_line(data=tigmac, aes(x=x, y=densityA), color = "black") +
  geom_line(data=tigmac, aes(x=x, y=densityB), color = "blue", linetype = "dashed") +
  geom_hline(aes(yintercept=0))+
  theme_bw() +
  theme(panel.border = element_blank(), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), axis.line = element_line(colour = "black")) +
  #geom_ribbon(aes(ymin=densityA, ymax=densityB), fill = "red", alpha=0.5)+
  xlab('Time') +
  ylab('Density of Activity')
p

I have provided photos to illustrate the overlap package plot output with the shaded in area and another how what my current ggplot2 plot looks like. 該代碼還將生成這些精確的圖。

重疊封裝-密度重疊 plot,重疊線之間的區域有陰影

ggplot2 封裝 - 重疊線之間的區域沒有陰影

我的最終結果是讓我的ggplot2 plot 與 plot 創建的overlap相同我想讓兩條重疊線之間的區域被遮蔽。

僅根據您希望 output 數據的外觀來判斷, geom_area()似乎可以解決問題。 您可以使用pmin()取成對最小值。

下面的例子。

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.3
library(overlap)
#> Warning: package 'overlap' was built under R version 4.0.4

data(kerinci)

timeRad <- kerinci$Time * 2 * pi

tig2 <- timeRad[kerinci$Zone == 2 & kerinci$Sps == 'tiger']
mac2 <- timeRad[kerinci$Zone == 2 & kerinci$Sps == 'macaque']

tigmac <- overlapPlot(tig2, mac2, main="Zone 2")

ggplot(tigmac, aes(x)) +
  geom_area(aes(y = pmin(densityA, densityB)),
            alpha = 0.3) +
  geom_line(aes(y = densityA, colour = "A")) +
  geom_line(aes(y = densityB, colour = "B"))

代表 package (v1.0.0) 於 2021 年 3 月 9 日創建

暫無
暫無

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

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