I have sample stock price data (in the end of this question) and I am trying to plot the geom_candlestick
chart and add different background colors for multiple date intervals using the following code:
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'))
Output:
I hope to remove extra legend part darkblue
and red
while keeping in_period
and out_period
only with scale_fill_discrete(name = "Period", label = c('in_period', 'out_period'), limits = c('in_period', 'out_period'))
.
Then I get a figure below as I uncomment last line of code:
I successfully removed unwanted legend part, but as you may notice, the candlestick's bar chart become same almost gray color which is different from the figure above.
So my question is how could I remove extra legend part while keeping same color effect as the first plot? Thanks.
Data:
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")