r - 使用 ggplot 的 stat_summary 更改主题和图例元素
问题描述
我有以下代码:
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函数,因为我认为这是问题所在,但我没有发现任何启发性的东西。
解决方案
labs
我使用更改color
和fill
参数的函数解决了图例名称的问题。在图中,我有颜色(即线条)和填充(即色带),因此必须更改两者以重命名图例。
我附上工作代码。
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_manual
andscale_fill_manual
来更好地可视化色带的重叠。为了重命名图例,我更改了函数的fill
andcolor
字段。labs()
推荐阅读
- python - openSMILE:在 python 中为 VAD 检测创建配置文件并运行信号处理
- python - elasticsearch.exceptions.ConnectionTimeout:由-ReadTimeoutError()引起的ConnectionTimeout
- node.js - 我们如何在不使用外部包和 tail -f 的情况下使用 node.js 继续查看大型日志文件并输出最后 10 行?
- graphql - Prisma 多对多关系查询
- c# - 让玩家以设定的长度冲向光标
- flutter - Firebase Googlemaps 错误不显示标记
- laravel-8 - 如何使用急切加载从雄辩的关系中仅返回json响应对象中的字符串列
- mysql - 标准化这些表的更好方法?
- amazon-web-services - 如何通过 AWS Billing 获取 EC2 实例成本
- java - Spring Boot 日志配置结合 Documentum