Add axis text above horizontal geom_bars; text alignment to the left

I would like to put the text axis above the corresponding horizontal stripes on the chart ggplot2. Below, as I understand it, with a subsequent schedule. Data is at the bottom of this question.

My questions , apart from the ubiquitous “which code is better to achieve the goal,” are (1) instead of manually entering a rectangle and text fields, how R can put them algorithmically, (2) how R can move text in rectangles to the far left (I tried with the calculation midpoint depending on the number of characters in the text, but that doesn't work)?

enter image description here

To plot, I created a sequence variable instead of struggling with as.numeric(as.character(risks).

ggplot(plotpg19, aes(x = sequence, y = scores)) +
  geom_bar(stat = "identity", width = 0.4) +
  coord_flip() +
  labs(x = "", y = "") +
  theme_bw() +
  theme(axis.text.y = element_blank(), axis.ticks.y = element_blank()) +
  geom_rect(data=plotpg19, aes(xmin= seq(1.5, 8.5, 1), 
                               xmax= seq(1.8, 8.8, 1), ymin=0, ymax=30), fill = "white") +
  geom_text(data=plotpg19, aes(x=seq(1.6, 8.6, 1), y= nchar(as.character(risks))/2, label=risks, size = 5, show_guide = FALSE)) +
  guides(size = FALSE)

.

plotpg19 <- structure(list(risks = structure(c(8L, 7L, 6L, 5L, 4L, 3L, 2L, 
1L), .Label = c("Other", "Third parties/associates acting on our behalf", 
"Rogue employees", "Lack of understanding by top executives", 
"Lack of anti-bribery/corruption training or awareness within the business", 
"Geographic locations in which the company operates", "Industries/sector(s) in which the company operates", 
"Inadequate resources for anti-bribery/corruption compliance activities"
), class = "factor"), scores = c(15, 28, 71, 16, 5, 48, 55, 2
), sequence = 1:8), .Names = c("risks", "scores", "sequence"), class = "data.frame", row.names = c(NA, 
-8L))

. geom_text geom_rect

+4
1

, geom_rect. y=0 aes of geom_text hjust=0 ( y) . x, :

library(dplyr)
plotpg19 <- mutate(plotpg19, xtext = sequence + 0.55)

library(ggplot2)
ggplot(plotpg19, aes(x = sequence, y = scores)) +
  geom_bar(stat = "identity", width = 0.4) +
  coord_flip() +
  labs(x = "", y = "") +
  theme_bw() +
  theme(axis.text.y = element_blank(), axis.ticks.y = element_blank()) +
  geom_text(data = plotpg19,
            aes(x = xtext, y = 0, label = risks, size = 5, show_guide = FALSE),
            hjust = 0, vjust = 1) +
  guides(size = FALSE)

enter image description here

+4

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


All Articles