r - R中的聚集(分组)条形图中的gghighlight

标签 r ggplot2 gghighlight

我需要在 R 中的集群条形图中使用 gghighlight 以便仅突出显示一个条形。我的代码和示例数据如下所示:

library(tidyr)
library(ggplot2)
dat <- data.frame(country=c('USA','Brazil','Ghana','England','Australia'), Stabbing=c(15,10,9,6,7), Accidents=c(20,25,21,28,15), Suicide=c(3,10,7,8,6))
dat.m <- melt(dat, id.vars='country')
dat.g <- gather(dat, type, value, -country)
ggplot(dat.g, aes(type, value)) + 
  geom_bar(aes(fill = country), stat = "identity", position = "dodge") +
  gghighlight(type == "Accidents" & country == "Brazil")

但这让我很尴尬

graph

我怎样才能让 gghighlight 只突出显示一个组中的一个条(因此结合两个离散变量的两个条件)?

最佳答案

这里有两个替代选项,用于在此类图中突出显示单个列:

1) 创建一个新变量(在下面命名为 highlight)并用它填充(如果你愿意,可以使用线条颜色按国家/地区着色)

2) 用箭头和/或文本手动注释要突出显示的一列(或弄清楚如何自动定位,但这会涉及更多)- 可能是一个最终数字的选项

library(tidyr)
library(ggplot2)
dat <- data.frame(country=c('USA','Brazil','Ghana','England','Australia'), 
    Stabbing=c(15,10,9,6,7), 
    Accidents=c(20,25,21,28,15), Suicide=c(3,10,7,8,6))
dat.m <- reshape2::melt(dat, id.vars='country')
dat.g <- gather(dat, type, value, -country)

## set highlighted bar
dat.g$highlight <- ifelse(dat.g$type == "Accidents" & dat.g$country == "Brazil", TRUE, FALSE)

## option 1: use fill to highlight, colour for country
ggplot(dat.g, aes(type, value, fill = highlight, colour=country), alpha=.6) + 
    geom_bar(stat = "identity", position = "dodge2", size=1) +
    scale_fill_manual(values = c("grey20", "red"))+
    guides(fill = FALSE) + 

    ## option 2: use annotate to manually label a specific column:
    annotate(geom = "curve", x = 1.15, y = 30, xend = 1.35, yend = 26, 
        curvature = .2, arrow = arrow(length = unit(2, "mm"))) +
    annotate(geom = "text", x = 1, y = 31, label = "Highlight", hjust = "left")

reprex package 创建于 2020-03-10 (v0.3.0)

关于r - R中的聚集(分组)条形图中的gghighlight,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60608210/

相关文章:

r - 根据循环中的一个标准在变量之间建立比率并保留多个变量

r - 从 sum() 和 '+' 获得不同的结果

r - 使用 ggplot2 翻转刻面标签和 x 轴

r - 在 ggplot2 中重新排序轴时,“eval(substitute(expr), e) : argument is missing, 中出现错误,无默认值”

将变量传递到函数中的 ggplot 中的正确方法,不要将其解释为 R 中的字符串

r - 使用 gghighlight 时为多个 geom_hlines 创建图例

R 友好的希腊字符

mysql - 按组计算时间差