Change Line Type for Certain Categories in Ggplot?

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.

1 Answer

This could be achieved as follows:

  1. Arrange your df by cat in descending order so that A and B come last
  2. Map the condition cat %in% c("A", "B") on linetype
  3. Set the linetypes for TRUE and FALSE using scale_linetype_manual
  4. get rid of the linetype legend using 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)

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)))
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest