更改 ggplot 中某些类别的线型?

tem*_*mor 3 r ggplot2

我有一些数据。

library(reshape2)
library(ggplot2)
df = data.frame(cat = LETTERS[1:6], VAR1 = runif(6), VAR2 = runif(6), VAR3 = runif(6), VAR4 = runif(6))
 df_melted = melt(df, id.vars = 'cat')
 ggplot(df_melted, aes(x = variable, y = value)) + geom_line(aes(color = cat, group = cat))
Run Code Online (Sandbox Code Playgroud)

我需要最后绘制 A 和 B(因此它们位于其他线条上方)并且线条类型为实线。其他“猫”的线型应该是虚线。

ste*_*fan 6

这可以通过以下方式实现:

  1. 按降序排列 df by cat,使 A 和 B 排在最后
  2. 将条件映射cat %in% c("A", "B")到线型上
  3. 使用以下命令将线型设置为 TRUE 和 FALSEscale_linetype_manual
  4. 使用摆脱线型图例guides
library(reshape2)
library(ggplot2)
df = data.frame(cat = LETTERS[1:6], VAR1 = runif(6), VAR2 = runif(6), VAR3 = runif(6), VAR4 = runif(6))
df_melted = melt(df, id.vars = 'cat')
df_melted <- arrange(df_melted, desc(cat))
#> Error in arrange(df_melted, desc(cat)): could not find function "arrange"
ggplot(df_melted, aes(x = variable, y = value)) + 
  geom_line(aes(color = cat, group = cat, linetype = cat %in% c("A", "B"))) +
  scale_linetype_manual(values = c("TRUE" = "solid", "FALSE" = "dotted")) +
  guides(linetype = FALSE)
Run Code Online (Sandbox Code Playgroud)

编辑实现结果的替代方法可能如下所示。这里我也使用同样的图案来调整大小。我喜欢这种方法的原因是我们不需要条件,并且只有一个图例:

library(reshape2)
library(ggplot2)
library(dplyr)

df = data.frame(cat = LETTERS[1:6], VAR1 = runif(6), VAR2 = runif(6), VAR3 = runif(6), VAR4 = runif(6))
df_melted = melt(df, id.vars = 'cat')
df_melted <- arrange(df_melted, desc(cat))
ggplot(df_melted, aes(x = variable, y = value, group = cat)) + 
  geom_line(aes(color = cat, linetype = cat, size = cat)) +
  scale_linetype_manual(values = c(A = "solid", B = "solid", rep("dotted", 4))) +
  scale_size_manual(values = c(A = 1, B = 1, rep(.5, 4)))
Run Code Online (Sandbox Code Playgroud)