I have some data.
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))
I need to plot A and B the last (so they are over other lines) and the type of lines to be solid. The line type for others "cat" should be dotted.
This could be achieved as follows:
cat %in% c("A", "B") on linetypescale_linetype_manualguideslibrary(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)

EDIT An alternative approach to achieve your result may look like so. Here I also use the same pattern to adjust the size. What I like about this approach is that we don't need a condition and we only have one legend:
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)))

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With