how to do it in ggplot2: custom legend and text box.

I'm trying to recreate the design of a @nexojornal graphic.
I don't know how to create the custom caption and text box

personalized legend
image

text box
image

cropped instagram graphic: link

I suppose that what they migth have done is draw a polygon under a text annotation:

library(ggplot2)

df <- data.frame(
  year = c(2000, 2001, 2002, 2003, 2004, 2005, 2006), 
  amt = c(1, 7, 6, 8, 8, 9, 7)
  )
df |>
ggplot()+
  coord_cartesian(clip = "off") +
  geom_line(aes(x = year, y = amt))+
  scale_x_continuous(expand = expansion(0, 1))+
  theme(aspect.ratio = 1/4)+
  geom_polygon(data = data.frame(x = c(2000, 2000.1, 2001, 2001, 2000),
                                 y = c(  -0,   -1,   -1,   -3,   -3)),
               aes(x,y),
               fill = "white", color= "black"
               )+
  annotate("text", 
           x = 2000.9, 
           y = -2, label = stringr::str_wrap("This is my text annotation", width = 18), 
           hjust = 1, vjust = .5, lineheight = .9)

The text box is outside the data plot area.

library(ggplot2)

df <- data.frame(
  year = c(2000, 2001, 2002, 2003, 2004, 2005, 2006), 
  amt = c(1, 7, 6, 8, 8, 9, 7)
)
df |>
  ggplot()+
  coord_cartesian(clip = "off") +
  geom_line(aes(x = year, y = amt))+
  scale_x_continuous(expand = expansion(0, 1))+
  theme(aspect.ratio = 1)

Yes, but if you're using ggplot(), @mduvekot's suggestion is good. You would just have to adjust everything else to fit above the text box.

1 Like

Text size depends on scale of the image you're rendering, which changes if you resize the Plot panel. In general, you shouldn't trust the Plots panel to show you what your final rendering that you're going to save with ggsave is going to look like. You can use the scale parameter is ggsave() to compensate, or use the {camcorder} package. For example, I would have used :

library(camcorder)
gg_record(
  dir = file.path(tempdir(),"recording"),
  device = c("png"), 
  scale = 1, width = 3000, height = 1000,
  units = "px", dpi = 300)
1 Like

Are there any packages that allow you to use html and css inline in titles and additional text?

{{ggtext}} has some (very) limited support.

update: the new {marquee} package has much improved support for markdown.