Paw in Data
Paw in Data

Reputation: 1554

How to specify colors and line types using columns in dataframe when using ggplot2 in R?

My dataframe df includes variables x, y, Color, and LineType. Can I specify the color and the line type automatically by the columns in df, while plotting line+marker chart with ggplot2?

library(ggplot2)

df = data.frame(x, y, Color, LineType)

P <- ggplot(DATA, aes(x=x.Years, y=y)) +
  geom_point(size=5, aes(color=Color)) +
  geom_line(aes(color=Color, linetype=LineType), size=2)

The code above doesn't work. There are two colors in Color and two line types in LineType, but everything come out red and in solid lines. What did I do wrong? How can I synchronize the plotting features of each data point?

Upvotes: 0

Views: 465

Answers (1)

StupidWolf
StupidWolf

Reputation: 46898

Not very sure what you mean or what went wrong with your plot, but if you want to manually specify colors using a data.frame, you do:

DATA = data.frame(x.Years=rep(1:5,2),y=c(1:5,8:12),
Color=rep(c("#dd7631","#708160"),each=5),
LineType = rep(c("dotted","dashed"),each=5))

ggplot(DATA,aes(x=x.Years,y=y)) + geom_point(aes(color=Color)) +
geom_line(aes(color=Color,linetype=LineType)) + 
scale_color_identity() + scale_linetype_identity()

enter image description here

Upvotes: 1

Related Questions