如何解决在ggplot2中创建自定义图例
所以,这是我的问题。
我有类似于下面要使用ggplot2
绘制的最小可重复示例的数据,其中一个数据框包含一个我想用作每个geom
的x值的列,以及多个我想要不同的y值。从下面的示例中可以看到,我想将geom_line
值的geom_point
和geom_point
与不同形状结合起来。
我现在的问题是,如何插入图例告诉我哪种形状代表什么列。到目前为止,从我对ggplot2
的了解中,通常会生成一个图例,如果我将某个因子(可能不是正确的术语)映射到color =
或group =
上,我错了吗?那么如果没有那个先决条件,我怎么还能得到一个图例?
非常感谢您的帮助!
library(tidyverse)
df <- structure(list(rep = c(1,1,1),Y_1 = c(0.0198,0.0108,0.0117,0.00931,0.0089,0.0115,0.00509,0.00831,0.0158,0.0437,0.0953,0.267,0.677,1.81),Y_2 = c(0.025,0.00249,0.00303,0.00268,0.0102,0.0112,0.0231,0.0326,0.0575,0.0852,0.143,0.219,0.384,0.687,1.01),X = c(0.1,0.164,0.268,0.439,0.72,1.18,1.93,3.16,5.18,8.48,13.9,22.8,37.3,61.1,100)),row.names = c(NA,15L),class = "data.frame")
df_plot <- ggplot(data = df) +
geom_line(mapping = aes(x = X,y = Y_1)) +
geom_point(mapping = aes(x = X,y = Y_1),shape = 15) +
geom_line(mapping = aes(x = X,y = Y_2)) +
geom_point(mapping = aes(x = X,y = Y_2),shape = 0) +
scale_x_log10() +
scale_y_log10() +
theme_classic()
df_plot
解决方法
创建图例的方法是将变量的不同级别映射到美学比例(在您的情况下为形状比例)。在ggplot
中执行此操作的最惯用的方法是将Y_1
和Y_2
设为y值的一列,并用新的列来标记每个y根据它来自的原始列的值。这意味着您只需要一次调用geom_line
和一次调用geom_point
:
ggplot(data = tidyr::pivot_longer(df,c("Y_1","Y_2"))) +
geom_line(mapping = aes(x = X,y = value,group = name)) +
geom_point(mapping = aes(x = X,shape = name)) +
scale_shape_manual(values = c(0,15)) +
scale_x_log10() +
scale_y_log10() +
labs(shape = "variable") +
theme_classic()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。