首页 > 解决方案 > 如何在条形图中的误差条和条形之间进行颜色叠加?

问题描述

我有一个带有误差线的条形图,我想对条形图和误差线使用相同的颜色。但是,这意味着我看不到错误栏的底部。

library(ggplot2)
library(tibble)

my_df <- 
  tibble::tribble(~response, ~estimate, ~lower_ci, ~upper_ci,
                  "little_bit", 0.353477, 0.255625, 0.451747,
                  "no", 0.307639, 0.250436, 0.375393,
                  "very", 0.338883, 0.301007, 0.37572310)

## compare this:
ggplot(my_df, aes(x = reorder(response, -estimate), y = estimate)) +
  geom_bar(stat = "identity", width = 0.9, fill = "#6EB3FF") +
  geom_errorbar(aes(ymin = lower_ci, ymax = upper_ci),
                width = 0.1, size = 3.5)

## with this:
ggplot(my_df, aes(x = reorder(response, -estimate), y = estimate)) +
  geom_bar(stat = "identity", width = 0.9, fill = "#6EB3FF") +
  geom_errorbar(aes(ymin = lower_ci, ymax = upper_ci),
                width = 0.1, size = 3.5, color = "#6EB3FF")

从到


我的视觉想法是使用覆盖


覆盖


gif

有没有办法实现这样的覆盖使用ggplot

标签: rggplot2errorbar

解决方案


一个简单的阿尔法就可以了。

请注意,从技术上讲,您不同的颜色。另一种选择是使用颜色修改包,例如shadescolorspaces。请参阅下面的一个选项colorspacesshades当你想改变整个调色板时很酷。

library(ggplot2)
library(tibble)

my_df <- 
  tibble::tribble(~response, ~estimate, ~lower_ci, ~upper_ci,
                  "little_bit", 0.353477, 0.255625, 0.451747,
                  "no", 0.307639, 0.250436, 0.375393,
                  "very", 0.338883, 0.301007, 0.37572310)

# super easy, just make the bars mor transparent - not quite your desired look
ggplot(my_df, aes(x = reorder(response, -estimate), y = estimate)) +
  geom_bar(stat = "identity", width = 0.9, fill = "#6EB3FF", alpha  = 0.7) +
  geom_errorbar(aes(ymin = lower_ci, ymax = upper_ci),
                width = 0.1, size = 3.5,color = "#6EB3FF")


## darkening the color, and adding some alpha for your desired effect
ggplot(my_df, aes(x = reorder(response, -estimate), y = estimate)) +
  geom_bar(stat = "identity", width = 0.9, fill = "#6EB3FF") +
  geom_errorbar(aes(ymin = lower_ci, ymax = upper_ci),
                width = 0.1, size = 3.5, 
                color = colorspace::darken("#6EB3FF"), alpha  = 0.7)


推荐阅读