Home > Mobile >  Add shape in ggplot followed by text
Add shape in ggplot followed by text

Time:08-24

I have below ggplot

library(ggplot2)
library(zoo)
dat = data.frame(date = as.yearmon(as.Date(c('2020-01-01', '2021-01-01', '2022-01-01', '2023-01-01', '2024-01-01', '2025-01-01', '2026-01-01','2027-01-01', '2028-01-01'))),
                    value = 1:9)

ggplot(data = dat)  
geom_line(aes(x = date, y = value))

Now I want to add some square which is followed by a text, as below

enter image description here

This should be place at the bottom of the plot but starting with x-position at 2020-05-01

Is there any way to achieve this?

CodePudding user response:

I may have misunderstood, but perhaps this will suit your use-case?

library(ggplot2)
library(zoo)
#> 
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#> 
#>     as.Date, as.Date.numeric
dat = data.frame(date = as.yearmon(as.Date(c('2020-01-01', '2021-01-01', '2022-01-01', '2023-01-01', '2024-01-01', '2025-01-01', '2026-01-01','2027-01-01', '2028-01-01'))),
                 value = 1:9)

ggplot(data = dat)  
  geom_line(aes(x = date, y = value))  
  geom_rect(aes(xmin = as.yearmon(as.Date(c('2020-05-01'))),
                xmax = as.yearmon(as.Date(c('2021-01-01'))),
                ymin = 0.5, ymax = 1),
            fill = "#5EB92A")  
  annotate("text",
           x = as.yearmon(as.Date(c('2021-02-01'))),
           y = 0.75, 
           label = "Add some text next to the green square", hjust = 0)

Created on 2022-08-23 by the reprex package (v2.0.1)


Or, if you want to plot the green square and text outside of the plot margins, you could use:

library(ggplot2)
library(zoo)
#> 
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#> 
#>     as.Date, as.Date.numeric
dat = data.frame(date = as.yearmon(as.Date(c('2020-01-01', '2021-01-01', '2022-01-01', '2023-01-01', '2024-01-01', '2025-01-01', '2026-01-01','2027-01-01', '2028-01-01'))),
                 value = 1:9)

ggplot(data = dat)  
  geom_line(aes(x = date, y = value))  
  geom_rect(aes(xmin = as.yearmon(as.Date(c('2020-05-01'))),
                xmax = as.yearmon(as.Date(c('2021-01-01'))),
                ymin = -0.75, ymax = -0.25),
            fill = "#5EB92A")  
  annotate("text",
           x = as.yearmon(as.Date(c('2021-02-01'))),
           y = -0.5, 
           label = "Add some text next to the green square", hjust = 0)  
  coord_fixed(clip = "off",ylim = c(1, 10))  
  theme(plot.margin = margin(0.1,0.1,1.5,0.1, "cm"))

Created on 2022-08-23 by the reprex package (v2.0.1)

  • Related