且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ggplot中合并颜色、线条样式和形状图例

更新时间:2023-08-30 17:37:45

以下是一般情况下的解决方案:

Here is the solution in the general case:

# Create the data frames
x <- seq(0, 10, by = 0.2)
y1 <- sin(x)
y2 <- cos(x)
y3 <- cos(x + pi / 4)
y4 <- sin(x + pi / 4)
y5 <- sin(x - pi / 4)
df1 <- data.frame(x, y = y1, Type = as.factor("sin"), Method = as.factor("method1"))
df2 <- data.frame(x, y = y2, Type = as.factor("cos"), Method = as.factor("method1"))
df3 <- data.frame(x, y = y3, Type = as.factor("cos"), Method = as.factor("method2"))
df4 <- data.frame(x, y = y4, Type = as.factor("sin"), Method = as.factor("method2"))
df5 <- data.frame(x, y = y5, Type = as.factor("sin"), Method = as.factor("method3"))

# Merge the data frames
df.merged <- rbind(df1, df2, df3, df4, df5)

# Create the interaction
type.method.interaction <- interaction(df.merged$Type, df.merged$Method)

# Compute the number of types and methods
nb.types <- nlevels(df.merged$Type)
nb.methods <- nlevels(df.merged$Method)

# Set the legend title
legend.title <- "My title"

# Initialize the plot
g <- ggplot(df.merged, aes(x,
                           y,
                           colour = type.method.interaction,
                           linetype = type.method.interaction,
                           shape = type.method.interaction)) + geom_line() + geom_point()
# Here is the magic
g <- g + scale_color_discrete(legend.title)
g <- g + scale_linetype_manual(legend.title,
                               values = rep(1:nb.types, nb.methods))
g <- g + scale_shape_manual(legend.title,
                            values = 15 + rep(1:nb.methods, each = nb.types))
# Display the plot
print(g)

结果如下:

  • 正弦曲线绘制为实线,余弦曲线绘制为虚线.
  • method1"数据使用实心圆作为形状.
  • method2"数据使用实心三角形作为形状.
  • method3"数据使用实心菱形作为形状.
  • 图例与曲线匹配

总而言之,技巧是:

  • 将类型/方法 interaction 用于所有数据表示(颜色、形状、线型等)
  • 然后手动设置曲线样式和图例样式scale_xxx_manual.
  • scale_xxx_manual 允许您提供比实际曲线数量更长的值向量,因此可以轻松地根据类型和方法因子的大小计算样式向量值
  • Use the Type/Method interaction for all data representations (colour, shape, linetype, etc.)
  • Then manually set both the curve styles and the legends styles with scale_xxx_manual.
  • scale_xxx_manual allows you to provide a values vector that is longer than the actual number of curves, so it's easy to compute the style vector values from the sizes of the Type and Method factors