首页 > 解决方案 > 从 ggplot2 图例中删除黑框

问题描述

经过一番谷歌搜索并环顾四周,我没有发现其他人有这个问题,也许我的措辞有误。但是,在我对 ggplot 2 的图例中,它在黑框周围显示与我的条相关的颜色,但不填充该框。它看起来像这样:

糟糕的传奇

这是我的代码

post_pre_active <- data.frame("survey" = c("pre", "pre", "pre", "pre", "pre", 
                                           "pre", "pre", "post", "post", "post",
                                           "post", "post", "post", "post"), 
                              "percentage" = c(14, 18, 16, 13, 11, 11, 17, 01, 07, 
                                               17, 18, 20, 10, 27),
                              "minutes" = c("0", "1-30", "31-60", "61-90", "91-120", 
                                            "121-150", "150+", "0", "1-30", "31-60", 
                                            "61-90", "91-120", "121-150", "150+"))
post_pre_active$minutes <- factor(post_pre_active$minutes, 
                                  levels = c("0", "1-30", "31-60", "61-90", 
                                             "91-120", "121-150", "150+"))
post_pre_active$survey <- factor(post_pre_active$survey, 
                                 levels = c("pre", "post"))

ggplot(post_pre_active, aes(x=minutes, y=percentage))+
  geom_bar(stat="identity", position="dodge", 
           aes(fill = survey, colour = survey))+
  scale_fill_discrete(name="Survey",
                      breaks=c(1, 2),
                      labels=c("Pre", "Post"))+
  xlab("Minutes of Physical Activity")+
  ylab("Percentage") +
  theme(legend.key = element_rect(colour = post_pre_active$survey,
                                  fill = post_pre_active$survey))

有任何想法吗?提前致谢。

标签: rggplot2

解决方案


看起来您的调用中有一些不必要的语法ggplot()会弄乱图例的绘制方式,因为填充和色标上的中断不匹配。您可以摆脱颜色美学,只留下填充,也可以摆脱breaks = c(1,2)一切应该工作的:

ggplot(post_pre_active, aes(x=minutes, y=percentage, fill=survey))+
  geom_bar(stat="identity",position="dodge")+
  scale_fill_discrete(name="Survey",
                      labels=c("Pre", "Post"))+
  xlab("Minutes of Physical Activity")+ylab("Percentage") 

推荐阅读