【问题标题】:Problem with "fill" argument data visualisation R, ggplot2“填充”参数数据可视化 R,ggplot2 的问题
【发布时间】:2021-12-27 15:24:50
【问题描述】:

我目前有一个关于“填充”参数如何为我的情节中的不同条形着色的问题。我希望对颜色进行预先确定的排名,以便我正在绘制的表格中的每个值都对应于一种颜色,而不是在我的情况下,它会发生变化。它在我的代码中的工作方式是我的表中的最大值对应于最亮的颜色(在默认的 ggplot 调色板中),而最小值对应于最暗的颜色。我的具体愿望是 100 应该对应于最亮的颜色,0 对应于最暗的颜色(因为我正在绘制分位数),当然,介于两者之间的所有内容。

这是我的代码。

library(tidyverse)

test <- tibble(factors=c("fact1","fact2","fact3","fact4"),
               percent=c(18.3,42.6,81.1,62.8))

ggplot(test) +
  geom_hline(
    aes(yintercept = y), 
    data.frame(y = c(0:4) * 25),
    color = "lightgrey"
  ) + 
  
  geom_col(
    aes(
      x = reorder(str_wrap((factors), 5), percent),
      y = percent,
      fill = percent
    ),
    position = "dodge2",
    show.legend = TRUE,
    alpha = .9,
    width=0.8
    
  ) +
  geom_segment(
    aes(
      x = reorder(str_wrap(factors, 5), percent),
      y = 0,
      xend = reorder(str_wrap(factors, 5), percent),
      yend = 100
    ),
    linetype = "dashed",
    color = "gray12"
  ) +
  
  scale_y_continuous(
    limits = c(-50, 100),
    expand = c(0, 0),
    breaks = c(0, 25, 50, 75,100)
  )+
coord_polar() 

如果您将“测试”标题的“百分比”部分中的值更改为 percent=c(80.1,80.5,80.1,79.9) 之类的值,您将很快理解我在说什么,就像在我的理想情况下一样,它应该只显示四个几乎相同的颜色,而不是从“百分比”列的最高到最低确定的颜色范围,显示从深到浅的颜色。

提前致谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    首先你应该创建一个调色板:

    my_palette <- colorRampPalette((RColorBrewer::brewer.pal(9, "Blues")))
    

    然后你可以在你的ggplot中添加scale_fill_gradientn

    test <- tibble(factors=c("fact1","fact2","fact3","fact4"),
                   # percent=c(18.3,42.6,81.1,62.8))
                   percent = c(80.1,80.5,80.1,79.9))
    
    
    ggplot(test) +
      geom_hline(
        aes(yintercept = y), 
        data.frame(y = c(0:4) * 25),
        color = "lightgrey"
      ) + 
      
      geom_col(
        aes(
          x = reorder(str_wrap((factors), 5), percent),
          y = percent,
          fill = percent
        ),
        position = "dodge2",
        show.legend = TRUE,
        alpha = .9,
        width=0.8
        
      ) +
      geom_segment(
        aes(
          x = reorder(str_wrap(factors, 5), percent),
          y = 0,
          xend = reorder(str_wrap(factors, 5), percent),
          yend = 100
        ),
        linetype = "dashed",
        color = "gray12"
      ) +
      
      scale_y_continuous(
        limits = c(-50, 100),
        expand = c(0, 0),
        breaks = c(0, 25, 50, 75,100)
      )+
      
      scale_fill_gradientn(colours = my_palette(100), 
                             limits=c(0,100))+
    
      coord_polar()
    

    【讨论】:

    • 完美运行!附带问题,是否有可能使颜色的顺序以一种简单的方式颠倒?
    • 可以指定my_palette(100)[100:1]倒序
    猜你喜欢
    • 2021-11-29
    • 2021-01-14
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多