r - 可能使用两种色标(解决方法)?
问题描述
我正在尝试将 18 个实验地块中 2 个物种的昆虫数量绘制到一个图表上。由于第二个物种的种群数量较晚达到峰值,因此在视觉上是可行的(见下图)。我希望物种 1 的 18 条种群线是绿色的(使用 RColorBrewer 的“Greens”),而物种 2 的 18 条种群线是红色的(使用“Reds”)。我确实意识到这对于色盲观众来说可能是个问题,但这在这里无关紧要。
我在这里读到,使用标准 ggplot2 选项是不可能的:R ggplot 在同一个图上使用两个调色板,但这篇文章已有两年多的历史了。
积分有一个“作弊”:使用两个比例颜色渐变 ggplot2但由于我更喜欢线条来显示时间的人口,所以我不能使用它。
是否有任何新的“作弊”可用?或者有没有人有其他想法来可视化我的数据,以在所有图中显示人口趋势随时间变化并显示峰值时间的差异?我在底部添加了一张图片,显示了我的真实数据,虽然都是相同的色标。
示例代码
# example data frame
plot <- as.factor(rep(c("A","B","C"),each=5))
time <- as.numeric(rep(c(1:5),times=3))
S1 <- c(1,4,7,5,2, 2,8,9,3,1, 1,6,6,3,1)
S2 <- c(0,0,2,3,2, 1,2,1,5,3, 0,1,1,6,7)
df <- data.frame(time, plot, S1, S2)
# example colour scales
S1Colours <- colorRampPalette(brewer.pal(9,"Greens"))(3)
S2Colours <- colorRampPalette(brewer.pal(9,"Reds"))(3)
names(S1Colours) <- levels(df$plot)
names(S2Colours) <- levels(df$plot)
# example plot
ggplot(data=df) +
geom_line(aes(x=time, y=S1, colour=plot)) +
geom_line(aes(x=time, y=S2, colour=plot)) +
scale_colour_manual(name = "plot", values = S1Colours) +
scale_colour_manual(name = "plot", values = S2Colours)
# this gives the note "Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale."
绘制真实数据
解决方案
我还会为所有组合创建手动色标。
library(tidyverse)
library(RColorBrewer)
df_long=pivot_longer(df,cols=c(S1,S2),names_to = "Species",values_to = "counts") %>% # create long format and
mutate(plot_Species=paste(plot,Species,sep="_")) # make identifiers for combined plot and Species
#make color palette
mycolors=c(colorRampPalette(brewer.pal(9,"Greens"))(sum(grepl("S1",unique(df_long$plot_Species)))),
colorRampPalette(brewer.pal(9,"Reds"))(sum(grepl("S2",unique(df_long$plot_Species)))))
names(mycolors)=c(grep("S1",unique(df_long$plot_Species),value = T),
grep("S2",unique(df_long$plot_Species),value = T))
# example plot
ggplot(data=df_long) +
geom_line(aes(x=time, y=counts, colour=plot_Species)) +
scale_colour_manual(name = "Species by plot", values = mycolors)
推荐阅读
- linux - 根据部分文本删除重复行
- keyboard - imac 上的大于符号不正确
- python - pygame中的精灵矩形
- node.js - CodeMix/Eclipse 找不到“反应/jsx-dev-runtime”
- python - voiceclient.play(discord.FFmpegPCMAudio) 不播放任何音频
- react-native - Xcode 13 构建错误 - 命令 PhaseScriptExecution 失败,退出代码为非零
- c# - 多对多关系ef核心中的默认关系
- python - TypeError:字符串索引必须是 sklearn 版本 0.24.2 的整数
- python-3.x - 在 python restapi 响应中显示列名
- c++ - ESP32 蓝牙连接状态