我在尝试着
(1) 使用一些变量作为因子创建一条线 ggplot 和
(2) 为颜色变量组之一(ID1 中的组“0”)设置特定颜色和较粗的线宽。
对于我的第一个问题,我不断收到错误消息:
“geom_path:每组只包含一个观察。你需要调整组美感吗?”
第二,我不知道从哪里开始。
我的数据如下所示:
ID1 ID2 Q V
503 503-2879 1 6.9
503 503-2879 2 14.21
503 503-2879 3 20.76
503 503-2879 6 36.64
503 503-2879 12 56.39
503 503-2879 20 68.87
503 503-2879 30 74.85
503 503-2879 40 76.87
504 504-2880 1 24.23
504 504-2880 2 34.41
504 504-2880 3 42.74
504 504-2880 6 59.7
504 504-2880 12 74.1
504 504-2880 20 79.04
504 504-2880 30 80.12
504 504-2880 40 80.27
755 755-3021 1 15.2
755 755-3021 2 19.5
755 755-3021 3 23.63
755 755-3021 6 35.02
755 755-3021 12 53.86
755 755-3021 20 72.57
755 755-3021 30 88.56
755 755-3021 40 99.01
0 N 1 1.526709
0 N 2 3.053418
0 N 3 4.580127
0 N 6 9.226632
0 N 12 18.453264
0 N 20 30.733313
0 N 30 46.06678
0 N 40 61.47
我的初始代码生成了一个非常接近我想要的图形(没有为“0”颜色组添加颜色和线宽设置)但是 X 轴是连续的,而实际上这个变量是分类的。
初始代码:
GPlot <- ggplot(VbyQG, aes(x = Q, y = V, color = ID1)) +
geom_path() +
theme_bw() +
theme(legend.position = 'none') +
theme_classic() +
theme(legend.position = 'none') +
expand_limits(y = 210)
GPlot
我希望 X 轴显示“Q”变量的正确中断和标签(1、2、3、6、12、20、30、40)。
我曾尝试在 ggplot aes() 中使用 str() 和 factor() 将“Q”变量更改为一个因子,但是这些更改中的任何一个都会处理错误消息并导致 X 轴显示正确的中断和标签,它们也会使所有数据消失。
我怎样才能让数据再次出现?另外,我需要添加什么样的编码来为颜色变量组之一(ID1 中的“0”组)设置特定颜色和更粗的线宽?
我已经为我的第二个问题寻找解决方案,但我找到的解决方案超出了我的初学者编码技能。再次感谢您的帮助!
对于第一个问题,这应该有效。这个想法是将 Q 转换为字符,然后使用 .cpp 中forcats
包含的包中的fct_reorder 使其成为有序因子tidyverse
。(我假设 Q 在您的来源中是数字。)
library(tidyverse)
df2 <- df %>%
# Takes Q, assumed numeric, saves as character, then converts to ordered factor
mutate(Q = as.character(Q) %>% fct_reorder(Q))
GPlot <- ggplot(df2, aes(x= Q, y = V, color = ID1, group = ID1)) +
geom_path() +
# Here's one way to highlight -- just draw on top with manual color & size
# geom_path(data = df2 %>% filter(ID1 == 503),
# size = 2, color = "slateblue") +
theme_bw() +
theme(legend.position = 'none') +
theme_classic() +
theme(legend.position = 'none') +
expand_limits(y = 210)
GPlot
要突出一个系列,最简单的方法可能是使用gghightlight
包。https://cran.r-project.org/web/packages/gghighlight/vignettes/gghighlight.html
或者您可以使用手动缩放颜色和厚度,并突出显示该系列。或者您可以使用手动定义的颜色和厚度在顶部绘制另一个图层,但这不会自动与任何图例标签集成。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句