【问题标题】:Change theme and legend elements with stat_summary of ggplot使用 ggplot 的 stat_summary 更改主题和图例元素
【发布时间】:2021-10-25 15:47:07
【问题描述】:

我有以下代码:

drawCombinedSeries <- function(data, xData, yData, dataGroup, title, fileName, outputPath) {
  
  plt <- ggplot(data, aes(x = xData, y = yData, fill = dataGroup)) +
    stat_summary(geom = "line", size=1, fun = mean, aes(color=dataGroup, group = dataGroup)) +
    stat_summary(geom = "ribbon", fun.data = mean_se, alpha = 0.3, aes(fill = dataGroup)) +
    labs(title = title, x="Month", y="") +
    theme(legend.position="bottom", axis.title.x = element_blank(), text = element_text(size=12, colour="black")) +
    scale_x_discrete(name = "Month", limits=c(1:12), expand = c(0,0)) 
  
  setwd(outputPath)
  ggsave(filename=fileName, width=10, height = 2.5)
  return(plt)
}

这个函数返回这个图:

我希望将线条的颜色更改为灰度,并重命名图例。

我尝试使用 theme_bw(),但它不起作用,因为我已经有了我的 theme()。关于图例,当我尝试创建自己的图例时,它只为最后一个 stat_summary 创建一个,即功能区,因此有两个图例。我一直在寻找一种方法来处理两个 stat_summary 函数,因为我认为这是问题所在,但我没有发现任何启发性的东西。

【问题讨论】:

  • 添加一点数据来玩总是很不错的 :-) 还有:您是如何尝试创建图例的?
  • 这里的颜色与theme 无关——它们是colorfill 美学。尝试将scale_fill_grey() + scale_color_grey() + 行添加到您的情节中 - 这应该可以解决问题。
  • @AllanCameron 没错,我一次只使用其中一个。解决方案是同时使用它们。谢谢!
  • @TobiO 图例是使用color/group 字段美学stat_summary 自动创建的。我不知道如何附加我正在使用的数据框(我是堆栈溢出的新手)。但是,我使用的数据是一些 github 存储库的活动,有 4 列:存储库的名称、活动量、索引(即月份,x 轴)和状态,即图例的数据组。我想重命名图例标题,但我没有找到办法。
  • 看看这里@RastaDeveloper :-) stackoverflow.com/questions/5963269/… 和你好 :wave: :-)

标签: r ggplot2


【解决方案1】:

我通过更改colorfill参数的labs函数解决了图例名称的问题。在图中,我有颜色(即线条)和填充(即色带),因此必须更改两者以重命名图例。

我附上工作代码。

drawCombinedSeries <- function(data, xData, yData, dataGroup, title, fileName, outputPath) {
  
  plt <- ggplot(data, aes(x = xData, y = yData, fill = dataGroup)) +
    stat_summary(geom = "line", size=.6, fun = mean, aes(color=dataGroup, group = dataGroup)) +
    stat_summary(geom = "ribbon", fun.data = mean_se, alpha = 0.25, aes(fill = dataGroup)) +
    labs(title = title, x="Month", y="", fill = "Status", color = "Status") +
    theme(legend.position="bottom", axis.title.x = element_blank(), text = element_text(size=12, colour="black"), panel.background = element_blank(), panel.grid = element_line(colour = "gray")) +
    scale_x_discrete(name = "Month", limits=c(1:12), expand = c(0,0)) +
    scale_fill_manual(values = c('Alive' = "#666666",'Zombie' = "#777777", 'Dead' = "#ffffff")) +
    scale_color_manual(values = c('Alive' = "#666666",'Zombie' = "#777777", 'Dead' = "#ffffff"))
  
  setwd(outputPath)
  ggsave(filename=fileName, width=10, height = 2.5)
  return(plt)
} 

我使用了scale_color_manualscale_fill_manual 来更好地可视化色带的重叠。为了重命名图例,我更改了labs() 函数的fillcolor 字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多