繁体   English   中英

线下的阴影区域 plot (ggplot2) 有 2 种不同颜色

[英]Shading area under a line plot (ggplot2) with 2 different colours

所以我有一个简单的数据集(真的是表),包含 2 个变量、一个日期和一个美元价值(损益)。 我正在尝试 plot 损益图,并且区域 y>0 以绿色阴影显示,y<0 红色(其中 y=Profit 或 Loss)。 我尝试了几种使用 ifelse 循环和 geom_area 的方法,但无济于事。

数据:根据要求,我收集数据的日期包括 4 月 14 日至 9 月 1 日。

dput(upl2$Unrealised.Profit.or.Loss)
c(87.5, -46, 163.5, 194.5, 251.5, 392, 276.5, 424, 354.5, 194, 
152, 104, 2, 0, 113, 78.5)

教授或损失的代码:

y <- upl2$Unrealised.Profit.or.Loss
loss <- y < 0 
prof <- y > 0
even <- y == 0 

plot 的代码:

ggplot(data = upl2, aes(x=Date, y=Unrealised.Profit.or.Loss, group=1)) + 
geom_point() + 
theme(axis.text.x = element_text(angle = 60, vjust = 0.5, hjust = 0.5)) + 
geom_line(size=.75) + 
geom_hline(yintercept=0, size=.5, color = "Blue") + 
labs(x = "Date", y = "Unrealised Profit or Loss", title = "Unreaslied Profit or Loss as of 7/6/2021")

任何建议都会很棒,
干杯

虽然对相交线之间的区域进行着色可能听起来很容易,但据我所知并非如此,而且我多次为这个问题苦苦挣扎。 原因是通常交点(在您的情况下是曲线的零点)不是数据的一部分。 因此,当尝试使用geom_areageom_ribbon对区域进行着色时,我们最终会在交点处出现重叠区域。 这个问题的更详细的解释可以在这篇文章中找到,它还通过使用approx提供了一个解决方案。

应用于您的用例

  1. 将您的Date变量转换为日期时间,因为我们希望在日期之间进行近似。
  2. 使用在日期之间插值并将“零”或交点添加到数据中的approx创建一个辅助数据框。 设置点数n需要反复试验,以确保没有肉眼可见的重叠。 在我看来n=500工作正常。
  3. 为损失和利润添加单独的变量,并使用例如lubridate::as_datetimeapprox返回的数字转换回日期时间。
  4. Plot 通过两个单独的geom_ribbon s 的阴影区域。

由于您没有提供示例数据,我的示例代码使用了一些随机的假数据:

library(ggplot2)
library(dplyr)
library(lubridate)

# Prepare example data

set.seed(42)

Date <- seq.Date(as.Date("2021-05-16"), as.Date("2021-06-07"), by = "day")
Unrealised.Profit.or.Loss <- runif(length(Date), -1, 1)

upl2 <- data.frame(Date, Unrealised.Profit.or.Loss)

# Prepare helper dataframe to draw the ribbons
upl2$Date <- as.POSIXct(upl2$Date)

upl3 <- data.frame(approx(upl2$Date,  upl2$Unrealised.Profit.or.Loss, n = 500))
names(upl3) <- c("Date", "Unrealised.Profit.or.Loss")

upl3 <- upl3 %>% 
  mutate(
    Date = lubridate::as_datetime(Date),
    loss = Unrealised.Profit.or.Loss < 0,
    profit = ifelse(!loss, Unrealised.Profit.or.Loss, 0),
    loss = ifelse(loss, Unrealised.Profit.or.Loss, 0))

ggplot(data = upl2, aes(x = Date, y = Unrealised.Profit.or.Loss, group = 1)) +
  geom_ribbon(data = upl3, aes(ymin = 0, ymax = loss), fill = "red") +
  geom_ribbon(data = upl3, aes(ymin = 0, ymax = profit), fill = "green") +
  geom_point() +
  geom_line(size = .75) +
  geom_hline(yintercept = 0, size = .5, color = "Blue") +
  scale_x_datetime(date_breaks = "day", date_labels = "%B %d") +
  theme(axis.text.x = element_text(angle = 60, vjust = 0.5, hjust = 0.5)) +
  labs(x = "Date", y = "Unrealised Profit or Loss", title = "Unreaslied Profit or Loss as of 7/6/2021")

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM