如何在ggplot2(R)的条形图中仅更改一个条形的geom_text的颜色和位置? [英] How to change colour and position of geom_text for just one bar in a barplot in ggplot2 (R)?

查看:95
本文介绍了如何在ggplot2(R)的条形图中仅更改一个条形的geom_text的颜色和位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ggplot2将条形图的值写入条形图来创建条形图.我仍然想用值"0"标记该组,但使用不同的颜色(黑色)并且在x轴上方.我该如何更改这一geom_text的位置和颜色?

I'm trying to create a bar plot with the depicted values written inside the bars using ggplot2. I still want to label the group with value "0" but in a different colour (black) and just above the x-axis. How can I change the position and colour of just this one geom_text?

我已经尝试过将矢量输入到scale_colour_manual中,但是它不起作用(或者我没有正确执行).

I've already tried entering a vector into scale_colour_manual but it didn't work (or I didn't do it right).

data <- read.table(text = "group percentage
               group1 30
               group2 29
               group3 0
               group4 18", header=TRUE)

library(ggplot2)
ggplot(data, aes(x=group, y=percentage))+
  theme_bw()+
  geom_bar(stat = 'identity', position = "dodge", fill="#13449f")+
  geom_text(aes(label = percentage), position = position_dodge(0.9), 
  vjust=1.3, colour = "white", size=6)

使用此代码,因为也不存在条,所以组3没有标签.我想在x轴上方仍保留一个黑色标签.

With this code there is no label for group3 since there is no bar either. I'd like to still have a label in black above the x-axis.

推荐答案

通过条件逻辑:

library(ggplot2)
ggplot(data, aes(x = group, y = percentage))+
    theme_bw()+
    geom_bar(stat = 'identity', position = "dodge", fill = "#13449f") +
    geom_text(aes(label = percentage), position = position_dodge(0.9), 
              vjust = ifelse(data$percentage > 3, 1.3, -0.3), 
              colour = ifelse(data$percentage > 3, "white", "black"), 
              size = 6)

这种方法有什么好处:

  • 它会自动处理大小的值
  • 您不需要第二个数据框或几何图形

这种方法的要点:

  • 什么是硬编码为>每次可视化都应校准3 .如果深入研究ggplot2如何构建图形,可能会自动化该部分,但是对于这个小例子来说,这可能会显得过份.
  • What is hardcoded as > 3 should be calibrated for each visualization. It is possible to automatize that part if you dive deeper into how ggplot2 builds graphs, but it would be overkill for this small example.

这篇关于如何在ggplot2(R)的条形图中仅更改一个条形的geom_text的颜色和位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆