Add a second signature to the polar coordinate based on the ggplot2 graph

I was asked to recreate the pie chart with ggplot2, and it's hard for me to add a second title to the plot. I need a signature at the bottom left of the plot and at the bottom right.

My current approach can get one or another option using the parameter hjustto place the title (0 for left justification, 1 for right justify):

library(ggplot2)
dat <- data.frame(variable = c("V1", "V2", "V3"),
                  value = c(.80,.50,.63))
p1 <- ggplot(dat, 
             aes(x = 1, y = value, fill = variable)) +
  geom_bar(stat = "identity") +
  coord_polar(theta = "y")  +
  theme(legend.position = 'none',
        plot.caption = element_text(hjust = 1)) +
  labs(caption  = "RIGHT CAPTION")

print(p1)

This gives:

Pie chart with right title.

I have seen some approaches that use annotate(), but I cannot get them to work with coord_polar().

Does anyone know how I can get the second heading that appears on the left side of the chart (horizontally aligned with the right caption)? Maybe you can impose an empty layer that has only a left caption?

+4
1

grid, , .

library(ggplot2)
library(grid)
dat <- data.frame(variable=c("V1", "V2", "V3"), value=c(.80,.50,.63))

p1 <- ggplot(dat, aes(x = 1, y = value, fill = variable)) +
  geom_bar(stat = "identity") +
  coord_polar(theta = "y") +
  theme(legend.position='none', plot.caption=element_text(hjust=1)) +
  labs(caption="RIGHT CAPTION")

# Generate a ggplot2 plot grob
p2 <- ggplotGrob(p1)
# Find the grob tree containing the right caption (as child)
k <- which(p2$layout$name=="caption")
# Copy the "right caption" text grob in grbTxt
grbTxt <- p2$grobs[[k]]$children[[1]]

# Modify content and position of the text grob  
grbTxt$label <- "LEFT CAPTION"
grbTxt$name <- "GRID.text.left"
grbTxt$x <- unit(0,"npc")
grbTxt$hjust <- 0
grbTxt$gp$col <- "red"

# Add grbTxt (left caption) to the title grob containing the right caption
p2$grobs[[k]] <- addGrob(p2$grobs[[k]],grbTxt)
grid.draw(p2)

enter image description here

+3

Source: https://habr.com/ru/post/1683701/


All Articles