【问题标题】:Add axis text above horizontal geom_bars; justify text flush left在水平 geom_bars 上方添加轴文本;对齐文本左对齐
【发布时间】:2015-10-09 15:37:40
【问题描述】:

我想在ggplot2 图中将轴文本置于适当的水平条之上。以下是我所得到的,之后是绘图代码。数据在这个问题的底部。

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

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

【问题讨论】:

    标签: r ggplot2 geom-bar geom-text


    【解决方案1】:

    我不明白您为什么要绘制白色 geom_rect。对于第二个问题,在geom_textaes 中设置y=0 并添加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)
    

    【讨论】:

    • 非常好,geom_text 本身看起来也不错。 R如何自动计算出 aes(x=seq(1.55, 8.55, 1) 起点和终点?
    • @lawyeR 恕我直言,最好自己设置。您可以直接在原始 data.frame 中而不是在 ggplot 命令中执行此操作(请参阅我的编辑)。您也可以将 x 映射到序列,然后使用 vjust,但我不推荐它(:geom_text(data=plotpg19, aes(x=sequence, y= 0, label=risks, size = 5, show_guide = FALSE),hjust=0,vjust=-3.5) 几乎可以解决问题,但您必须手动调整绘图高度。
    猜你喜欢
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    相关资源
    最近更新 更多