我有样本股票价格数据(在这个问题的结尾),我正在尝试绘制geom_candlestick
图表并使用以下代码为多个日期间隔添加不同的背景颜色:
library(ggplot2)
library(tidyquant)
library(lubridate)
data$date <- as.Date(data$date, format='%Y/%m/%d')
rects <- data.frame(
xstart = as.Date(c('2021/12/1', '2021/12/9'), format = '%Y/%m/%d'),
xend = as.Date(c('2021/12/8', '2021/12/17'), format = '%Y/%m/%d'),
col = c('in_period', 'out_period')
)
ggplot(data=data, aes(x = as.Date(date))) +
geom_candlestick(aes(open = open, high = high, low = low, close = close), alpha=0.6) +
scale_x_date(breaks = "3 days", date_labels = "%Y-%m-%d") +
geom_rect(data = rects, aes(xmin = xstart, xmax = xend, ymin = -Inf, ymax = Inf, fill = col), alpha = 0.4, inherit.aes = FALSE)
# + scale_fill_discrete(name = "Period", label = c('in_period', 'out_period'), limits = c('in_period', 'out_period'))
输出:
我希望删除额外的图例部分darkblue
,red
同时保留in_period
并且out_period
仅使用scale_fill_discrete(name = "Period", label = c('in_period', 'out_period'), limits = c('in_period', 'out_period'))
.
然后我在取消注释最后一行代码时得到下图:
我成功删除了不需要的图例部分,但您可能会注意到,烛台的条形图变成了与上图相同的几乎灰色的颜色。
所以我的问题是如何在保持与第一个图相同的颜色效果的同时删除额外的图例部分?谢谢。
数据:
data <- structure(list(date = structure(c(18962, 18963, 18964, 18965,
18966, 18967, 18968, 18969, 18970, 18971, 18972, 18973, 18974,
18975, 18976, 18977, 18978), class = "Date"), open = c(1360L,
1333L, 1341L, 1412L, 1452L, 1455L, 1487L, 1510L, 1502L, 1491L,
1530L, 1520L, 1495L, 1485L, 1507L, 1500L, 1490L), high = c(1360L,
1349L, 1387L, 1456L, 1467L, 1503L, 1507L, 1552L, 1518L, 1540L,
1543L, 1532L, 1504L, 1508L, 1528L, 1506L, 1520L), low = c(1334L,
1316L, 1340L, 1410L, 1425L, 1445L, 1474L, 1506L, 1468L, 1483L,
1518L, 1488L, 1471L, 1475L, 1498L, 1489L, 1490L), close = c(1334L,
1344L, 1387L, 1456L, 1458L, 1486L, 1484L, 1515L, 1503L, 1532L,
1531L, 1489L, 1491L, 1504L, 1505L, 1496L, 1504L)), row.names = c(NA,
-17L), class = "data.frame")