在 R 中使用 ggplot2 时,如何使用数据框中的列来指定颜色和线条类型?

问题描述 投票:0回答:1

我的数据框 df 包括变量 x, y, ColorLineType. 我是否可以通过列自动指定颜色和线型?df绘制线+标记图时,用的是 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)

上面的代码不能用。有两个颜色在 Color 和两行类型 LineType但所有的东西都是红色的,而且是实线。我做错了什么?如何同步每个数据点的绘图特征?

r data-visualization ggplot2
1个回答
1
投票

不是很清楚你的意思,也不知道你的图出了什么问题,但是如果你想用data.frame手动指定颜色,你可以。

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

© www.soinside.com 2019 - 2024. All rights reserved.