Reputation: 1554
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
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()
Upvotes: 1