SteveG
SteveG

Reputation: 109

Adding geom_text() to ggplot_calendar_heatmap()

I've been trying to add overlay text to a calendar. I have a simple set of 6 groups that provide the colour for each cell. Now I want to add a running count of days in each group (in character format).

When I take https://github.com/AtherEnergy/ggTimeSeries/blob/master/R/ggplot_calendar_heatmap.R as a source it shows (lines 72-75)

#' p1
#' # add new geoms
#' p1 +
#' geom_text(label = '!!!')

Now this works with a fixed text but I want to vary the text cell-by-cell. Note that aes(x, y) isn't used in ggplot_calendar_heatmap.

StudyDates %>%
ggplot_calendar_heatmap(
'Date',
'NotWorked',
vcGroupingColumnNames = "Year",
dayBorderSize = 0.2,
monthBorderSize = 0.5
)

I don't see how to 'transfer the data aes() elements from the above to ...

geom_text(StudyDates, 
aes('Date','NotWorked',
label = LabelDay,
),
size=1)

Does anyone have a suggestion?

Thanks

Upvotes: 0

Views: 80

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173988

You can pass a vector of text the same length as the vector of dates:

library(ggTimeSeries)

set.seed(1)
df <- data.frame(date = seq(as.Date('2022-01-01'), as.Date('2022-02-28'),
                            by = 'day'),
                 value = cumsum(rnorm(59)),
                 letter = sample(LETTERS, 59, TRUE))

p1 <- ggplot_calendar_heatmap(df, 'date', 'value') +
      scale_fill_continuous(low = 'green', high = 'red')

p1 + geom_text(label = df$letter)

enter image description here

In your case it seems you have a categorical fill variable, and you want the label to represent the number of consecutive days that a particular category of the fill variable appears. In that case, the following might be closer to what you want:

set.seed(1)
df <- data.frame(date = seq(as.Date('2022-01-01'), as.Date('2022-02-28'),
                            by = 'day'),
                 Notworked = sample(c('A', 'B', 'C'), 59, TRUE),
                 letter = sample(LETTERS, 59, TRUE))
df$count <- 1
for(i in seq(nrow(df))[-1]) {
  if(df$Notworked[i] == df$Notworked[i - 1]) 
    df$count[i] <- df$count[i - 1] + 1
  else
    df$count[i] <- 1
    
}

p1 <- ggplot_calendar_heatmap(df, 'date', 'Notworked') +
      scale_fill_manual(values = c('steelblue', 'pink', '#F0F0AA'))

p1 + geom_text(label = df$count)

enter image description here

Upvotes: 1

Related Questions