繁体   English   中英

更改ggplot条形图填充colors

[英]Change ggplot bar chart fill colors

有了这些数据:

df <- data.frame(value =c(20, 50, 90), 
                 group = c(1, 2,3))

我可以得到一个条形图:

df %>% ggplot(aes(x = group, y = value, fill = value)) +
  geom_col() +
  coord_flip()+ 
  scale_fill_viridis_c(option = "C") +
  theme(legend.position = "none")

在此处输入图像描述

但我想让这些条形图的 colors 根据它们在value中的相应值而变化。

我已经设法使用geom_raster更改它们:

ggplot() + 
  geom_raster(aes(x = c(0:20), y = .9, fill = c(0:20)),  
              interpolate = TRUE) +
  geom_raster(aes(x = c(0:50), y = 2, fill = c(0:50)), 
              interpolate = TRUE) +
  geom_raster(aes(x = c(0:90), y = 3.1, fill = c(0:90)),               
              interpolate = TRUE) +
  scale_fill_viridis_c(option = "C") +
  theme(legend.position = "none")

在此处输入图像描述

当我在真实数据中有很多组时,这种方法效率不高。 任何能更有效地完成它的建议将不胜感激。

我找到了先前类似问题的公认答案,但是“这些数字需要根据 x 值的数量和 y 的范围进行调整”。 我一直在寻找一种不必根据数据调整数字的方法。 大卫吉布森的回答符合我的目的。

看起来这在 ggplot 中不受本地支持。 通过向数据添加从 0 到value ) 的额外行,我能够得到一些接近的东西。 然后使用geom_tile并通过指定width分隔图块。

library(tidyverse)

df <- data.frame(value = c(20, 50, 90),
                 group = c(1, 2, 3))

df_expanded <- df %>%
  rowwise() %>%
  summarise(group = group,
            value = list(0:value)) %>%
  unnest(cols = value)

df_expanded %>%
  ggplot() +
  geom_tile(aes(
    x = group,
    y = value,
    fill = value,
    width = 0.9
  )) +
  coord_flip() +
  scale_fill_viridis_c(option = "C") +
  theme(legend.position = "none")

在此处输入图像描述

如果这太像素化了,您可以通过将list(0:value)替换为seq(0, value, by = 0.1)来增加生成的行数。

在此处输入图像描述

这是使用 ggforce 的真正 hack。 这个 package 有一个可以采用颜色渐变的几何图形,但它是用于线段的。 我刚刚增加了尺寸,使线段看起来像条形。 我让所有的条形长度相同以获得正确的渐变,然后用与背景颜色相同的颜色覆盖每个条形的一部分,使它们看起来是正确的长度。 但是,必须隐藏网格线。 :-)

df %>% 
    ggplot() + 
    geom_link(aes(x = 0, xend = max(value), y = group, yend = group, color = stat(index)), size = 30) +
    geom_link(aes(x = value, xend = max(value), y = group, yend = group), color = "grey", size = 31) +
    scale_color_viridis_c(option = "C") +
    theme(legend.position = "none", panel.background = element_rect(fill = "grey"), 
          panel.grid = element_blank()) +
    ylim(0.5, max(df$group)+0.5 )

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM