Hausdorff
Hausdorff

Reputation: 47

ggplot line with multiple colors by a factor

The following codes plot the first graph. but I want to color the lines by the variable factor1. Is there a simple way?

data <- data.frame(factor1 = c(1,1,1,1,1,1,2,2,2,2,2,2),
                   factor2 = c(1,1,1,2,2,2,3,3,3,4,4,4),
                         x = c(1,2,3,1,2,3,1,2,3,1,2,3),
                         y = c(1,2,3,4,5,6,11,12,13,14,15,16)
                   )

p <- ggplot2::ggplot(data, aes(x, y, colour = factor(factor2))) +
  ggplot2::geom_line( )

print(p)

The current output:

My desired output:

Upvotes: 1

Views: 2450

Answers (2)

ives
ives

Reputation: 1400

I believe your colour option is providing a hint to the grouping. Try the following instead:

p <- ggplot2::ggplot(data)
p +
  aes(x, y, group = factor(factor2), colour = factor(factor1)) + 
  geom_line()

This should result in the following graph:

plot with factored grouping & color

If you want to show the legend for each of the series in the group, you can add another geometry like point shapes:

p +
  aes(x, y) +
  aes(
    group = factor(factor2),
    shape= factor(factor2),
    color = factor(factor1)
  ) +
  geom_line() +
  geom_point() +
  labs(shape="factor1", colour="factor2")

Which will result in the following:

enter image description here

If you'd like to have more control over graph, you might consider reshaping the data.

See the following for additional information about formatting legends with multiple groups:

R Graph Gallery (custom layout legend)

R Cookbook (legends)

Upvotes: 1

stefan
stefan

Reputation: 123818

To color by factor1, while drawing lines for groups given by factor2, map factor1 on color aesthetic and factor2 on group aesthetic (Note: To make clear why there are two lines with same colors I would suggest to map factor2 on shape, linewidth ...).

library(ggplot2)

data <- data.frame(factor1 = c(1,1,1,1,1,1,2,2,2,2,2,2),
                   factor2 = c(1,1,1,2,2,2,3,3,3,4,4,4),
                   x = c(1,2,3,1,2,3,1,2,3,1,2,3),
                   y = c(1,2,3,4,5,6,11,12,13,14,15,16)
)

# Plot with lines colored by factor1.
# Map factor1 on color and factor2 on group
p <- ggplot2::ggplot(data, 
                     aes(x, y, 
                         colour = factor(factor1), 
                         group = factor(factor2))) +
  ggplot2::geom_line() 
p

Created on 2020-03-08 by the reprex package (v0.3.0)

Upvotes: 0

Related Questions