如何突出显示ggplot2中的列

我有下面的图,我想突出显示两个西瓜的列,因为它的juice_content和重量最高。我知道如何更改列的颜色,但我想突出显示整个列。关于如何实现这一点的任何想法?网上似乎没有任何类似的内容。

fruits <- c("apple","orange","watermelons")
juice_content <- c(10,1,1000)
weight <- c(5,2,2000)
df <- data.frame(fruits,juice_content,weight)
df <- gather(df,compare,measure,juice_content:weight,factor_key=TRUE)
plot <- ggplot(df,aes(fruits,fill=compare)) + geom_bar(stat="identity",position=position_dodge()) + scale_y_log10()

如何突出显示ggplot2中的列

qq626113468 回答:如何突出显示ggplot2中的列

一种选择是使用gghighlight

library(gghighlight)
ggplot(df,aes(fruits,measure,fill = compare)) +
    geom_col(position = position_dodge()) +
    scale_y_log10() +
    gghighlight(fruits == "watermelons")

enter image description here


根据您的评论,如何使用不同的alpha

ggplot(df,measure)) +
    geom_col(data = . %>% filter(fruits == "watermelons"),mapping = aes(fill = compare),position = position_dodge()) +
    geom_col(data = . %>% filter(fruits != "watermelons"),alpha = 0.2,position = position_dodge()) +
    scale_y_log10()

enter image description here


或者您也可以使用一个geom_col和一个有条件的alpha(感谢@Tjebo)来实现相同的目标

ggplot(df,measure)) +
    geom_col(
        mapping = aes(fill = compare,alpha = fruits == 'watermelons'),position = position_dodge()) +
    scale_alpha_manual(values = c(0.2,1)) +
    scale_y_log10()
,

您可以使用geom_area突出显示栏后面。您必须先将x比例尺强制设为离散,这就是为什么我使用geom_blank(请参见答案geom_ribbon overlay when x-axis is discrete)的原因,并指出geom_ribbongeom_area实际上是相同的,除了geom_area的ymin始终为0

#minor edit so that the level isn't hard coded
 watermelon_level <- which(levels(df$fruits) == "watermelons")

AreaDF <- data.frame(fruits = c(watermelon_level-0.5,watermelon_level+0.5))


plot <- ggplot(df,aes(fruits)) + 
  geom_blank(aes(y=measure,fill=compare))+
  geom_area(data = AreaDF,aes( y = max(df$measure)),fill= "yellow")+
  geom_bar(aes(y=measure,fill=compare),stat="identity",position=position_dodge()) + scale_y_log10()

enter image description here

编辑以发表评论

如果要突出显示多个水果,则可以执行以下操作。您需要一个data.frame,其中要包含geom_area x和y的位置,包括将它们之间的距离降低到0。我敢肯定,获取data.frame的方法略微一些,但这是可行的

highlight_level <- which(levels(df$fruits) %in% c("apple","watermelons"))

AreaDF <- data.frame(fruits = unlist(lapply(highlight_level,function(x) c(x -0.51,x -0.5,x+0.5,x+0.51))),yval = rep(c(1,max(df$measure),1),length(highlight_level)))




AreaDF <- AreaDF %>% mutate(
  yval = ifelse(floor(fruits) %in% highlight_level & ceiling(fruits) %in% highlight_level,yval)) %>%
  arrange(fruits) %>% distinct()


plot <- ggplot(df,aes(y = yval ),position=position_dodge()) + scale_y_log10()
plot

enter image description here

本文链接:https://www.f2er.com/3099318.html

大家都在问