【问题标题】:How to fill (color) bars in a bar chart a different color within the bar itself up to a certain number?如何在条形图中填充(颜色)条形图本身的不同颜色,最多达到一定数量?
【发布时间】:2021-12-30 21:19:22
【问题描述】:

groups <- data.frame(group = c("A", "B"),
                                Reels = c(155, 343),
                                Fish = c(41, 221))
groups %>% 
  ggplot(aes(x = group, y = Reels)) + 
  geom_col() +
  labs(
    x = "Group",
    y = "Count"
  ) 

我想在这张图表中的条形图中填充捕获的鱼的数量。所以你可以在图表上看到不同的颜色。我想我会使用 fill 参数,但我无法让该值在 41/155 处截止。

类似于https://r4ds.had.co.nz/data-visualisation.html 第 3.8 节,他们根据钻石净度为图表着色。

我的目标是两根高分别为 155 和 343 的酒吧 - 一根用于 A,一根用于 B。然后我想给鱼(41/155)的数量上色。有什么建议吗?如果需要进一步说明,请告诉我。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    r2evans 的答案是 #1 :) 只是为了记录,我认为fill 在这种情况下不起作用,因为数据不是 ggplot-ready?

    library(tidyverse)
    groups <- data.frame(group = c("A", "B"),
                         Reels = c(155, 343),
                         Fish = c(41, 221))
    reshape2::melt(groups) %>% 
      ggplot(aes(x = group, y = value, fill = variable)) + 
      geom_col() +
      labs(
        x = "Group",
        y = "Count"
      ) 
    
    

    【讨论】:

      【解决方案2】:

      试试这个,加上一个文本标签,效果很好:

      groups %>% 
        ggplot(aes(x = group, y = Reels)) + 
        geom_col(aes(y = Fish), fill = "red") +
        geom_col(fill = "transparent", color = "black") +
        geom_text(aes(y = Fish + 1, label = paste(Fish, Reels, sep = " / ")), vjust = -0.5) +
        labs(
          x = "Group",
          y = "Count"
        ) 
      

      【讨论】:

        猜你喜欢
        • 2020-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-01
        • 1970-01-01
        相关资源
        最近更新 更多