在水平geom_bars上方添加轴文本;证明文本冲洗左

时间:2015-07-20 13:26:52

标签: r ggplot2 geom-bar geom-text

我想在ggplot2图中将轴文本放在上方的相应水平条上。以下是我得到的,后面的绘图代码。数据位于这个问题的底部。

我的问题,除了永远存在的“什么代码可以更好地实现目标”之外,还有(1)而不是我手动输入矩形和文本位置,R如何通过算法放置它们, (2)R如何将矩形中的文本移动到最左边(我尝试根据文本中的字符数计算中点,但它不起作用)?

enter image description here

对于绘图我创建了序列变量而不是与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))

这个问题给了我一些指导。 fitting geom_text inside geom_rect

1 个答案:

答案 0 :(得分:4)

我不明白你为什么要策划白色geom_rect。对于第二个问题,在y=0的{​​{1}}中设置aes并添加geom_text(正好以y开头的文字)有效。我调整了x参数,以便在条形图中间绘制文本:

hjust=0

enter image description here