gpt4 book ai didi

r - 在 ggplot2 中创建自定义图例

转载 作者:行者123 更新时间:2023-12-04 08:42:24 37 4
gpt4 key购买 nike

所以,这是我的问题。
我有类似于下面的最小可重现示例的数据,我想用 ggplot2 进行绘图,其中数据框包含一列,我想将其用作每个 geom 的 x 值以及我想要作为不同 y 值的几列。从下面的例子可以看出,我想结合geom_linegeom_point geom_point 的不同形状值(value)观。
我现在的问题是,如何插入一个图例来告诉我哪个形状代表哪些列。根据我对 ggplot2 的了解到目前为止,如果我将某些因素(可能不是正确的术语)映射到 color =,通常会生成一个图例或 group = , 我错了?那么没有这个先决条件,我怎么还能得到一个传奇呢?
非常感谢您的帮助!

library(tidyverse)

df <- structure(list(rep = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1), Y_1 = c(0.0198, 0.0108, 0, 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 将您的数据 reshape 为长格式和 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, y = value, shape = name)) +
scale_shape_manual(values = c(0, 15)) +
scale_x_log10() +
scale_y_log10() +
labs(shape = "variable") +
theme_classic()
enter image description here

关于r - 在 ggplot2 中创建自定义图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64496037/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com