这是我要绘制的数据框:
age composite_col frequency
1 18 var1 0.65531200
2 19 var1 0.48697446
3 20 var1 0.21423509
4 21 var1 0.38887071
5 22 var1 0.27072698
6 23 var1 0.76371308
7 18 var2 0.05554554
8 19 var2 0.65048383
9 20 var2 0.98546390
10 21 var2 0.04171436
11 22 var2 0.13346492
12 23 var2 0.21246432
以下是用于生成数据框的代码:
library(tidyr)
set.seed(1911)
df_se = data.frame(age = c(18,19,20,21,22,23), var1 = runif(6,0,1), var2 = runif(6,0,1) )
df_se = gather(df_se, "composite_col","frequency",c(var1,var2))
df_se
我想生成一个包含以下内容的图形:
composite_col
决定composite_col
指示的颜色和形状覆盖geom_points 我试图解决的问题:
p = ggplot(data = df_se)
p = p + geom_line( aes(x=age, y=frequency, colour=composite_col) )
p = p + geom_point(aes(x = age, y= frequency, shape = composite_col, fill = composite_col, colour = "black"), pch = 21, size = 2.5)
p = p + scale_colour_manual(values=c("#DF4A2A", "#3D9813"))
p
产生以下错误:
Error: Insufficient values in manual scale. 3 needed but only 2 provided.
当我向调色板中添加更多颜色时,它会生成一个图形,但是颜色是完全错误的,比例是完全错误的
答案 0 :(得分:1)
由于每个点的轮廓应始终为黑色,因此您需要在colour = "black"
调用之外删除aes()
行。
ggplot(data = df_se, aes(x=age, y=frequency)) +
geom_line(aes(colour=composite_col)) +
geom_point(aes(shape=composite_col, fill=composite_col), colour="black", pch=21, size=2.5) +
scale_colour_manual(values=c("#DF4A2A", "#3D9813"))
如果您希望点的颜色与线的颜色匹配,则可以为填充添加比例:
ggplot(data = df_se, aes(x=age, y=frequency)) +
geom_line( aes(colour=composite_col) ) +
geom_point(aes(shape = composite_col, fill = composite_col), colour = "black", pch = 21, size = 2.5) +
scale_colour_manual(values=c("#DF4A2A", "#3D9813")) +
scale_fill_manual(values=c("#DF4A2A", "#3D9813"))
编辑:
要使用scale_shape_manual
指定形状,您需要从pch
中删除geom_point
参数:
ggplot(data = df_se, aes(x=age, y=frequency)) +
geom_line( aes(colour=composite_col) ) +
geom_point(aes(shape = composite_col, fill = composite_col), colour = "black", size = 2.5) +
scale_colour_manual(values=c("#DF4A2A", "#3D9813")) +
scale_fill_manual(values=c("#DF4A2A", "#3D9813")) +
scale_shape_manual(values=c(3, 16))