【问题标题】:GGPlot is returning different colours to what I specifyGGPlot 将不同的颜色返回到我指定的颜色
【发布时间】:2020-12-19 12:32:00
【问题描述】:

我对 R 有点陌生 - 在尝试制作以下情节时遇到了一个非常奇怪的问题


worst_death <- df_clean %>%
        group_by(event_cat) %>%
        summarise(Deaths = sum(FATALITIES)
                  , Injuries = sum(INJURIES)) %>%
        ggplot()+
        geom_segment(aes(x=reorder(event_cat,Injuries),xend=reorder(event_cat,Injuries), y=Deaths, yend = Injuries, color="black")) +
        geom_point(aes(x=reorder(event_cat,Injuries), y=Deaths,color="yellow", size=1 ))+
        geom_point(aes(x=reorder(event_cat,Injuries), y=Injuries,color="white", size=1 ))+
        coord_flip()+
        theme_ipsum()+
        theme(legend.position = "none",) +
        xlab("Event Type") +
        ylab("Human Impact")
        
        

worst_death

图表运行完美 - 除了颜色和美学选项(大小等)没有返回我指定的内容。

奇怪的是颜色是红色蓝色和绿色,而不是黄色黑色和白色。

有人知道为什么会这样吗?

谢谢

【问题讨论】:

    标签: r ggplot2 visualization


    【解决方案1】:

    如果没有您的数据,我无法对此进行测试,但以下内容应该适合您:

    worst_death <- df_clean %>%
            group_by(event_cat) %>%
            summarise(Deaths = sum(FATALITIES),
                      Injuries = sum(INJURIES)) %>%
            ggplot(aes(x = reorder(event_cat,Injuries), y = Deaths)) +
            geom_segment(aes(xend = reorder(event_cat,Injuries), 
                             y = Deaths, yend = Injuries)) +
            geom_point(color = "yellow", size = 1) +
            geom_point(aes(y = Injuries), color = "white", size = 1) +
            coord_flip() +
            theme_ipsum() +
            theme(legend.position = "none") +
            xlab("Event Type") +
            ylab("Human Impact")
            
    worst_death
    

    有几点需要注意:

    • 当您使用字符串表示颜色 inside aes 时,ggplot 将其读取为将几何图形分配给标记颜色 grouping 的单因子级别,并将不要将其解释为文字颜色分配。如果您的情节中有一个图例,则该键将在红色和蓝色键点上显示标签“白色”和“黄色”。如果您希望这些标签被解释为文字颜色,您可以将+ scale_color_identity() 添加到您的绘图中,或者更常见的是,只需将aescolor = outside 带入,它被解释为实际颜色分配。如果您不想要图例,这是最简单的方法。
    • 您可能也应该将size = 带到aes 调用之外,实际上是出于同样的原因。 ggplot 将数字 1 映射到其默认大小比例,而不是真正将点大小设为 1。
    • geom_segment 默认为黑色,因此不需要指定颜色。
    • 如果您在原始 ggplot 调用中包含默认的 x 和 y 美学,您可以节省一些输入(从而降低错误风险并使维护更容易)。这些被任何后续的 geom 继承,但如果需要可以被覆盖。
    • 在 SO 上发布问题时,请包括数据和代码,否则没有人可以重现您的问题或测试/演示可能的解决方案。在您的情况下,最简单的方法是将dput(df_clean) 的输出复制并粘贴到您的问题中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2018-10-02
      • 1970-01-01
      • 2017-11-04
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多