r - 如何独立更改图例中的颜色线条大小和形状大小?

标签 r ggplot2

我有一个线图,我将颜色和形状组合到同一个图例中。我希望图例中的点尺寸更大,图例中的线保持不变,以便形状更清晰。

来自 How to increase the size of points in legend of ggplot2?我知道可以通过 + guides(colour = guide_legend(override.aes = list(size=10))) 更改点的大小,但是这也会改变行的大小。如果我添加 guides(shape = guide_legend(override.aes = list(size=4)),color = guide_legend(override.aes = list(size=1)))它说`重复的覆盖.aes 被忽略,只使用第二个大小。

如何独立更改图例中的颜色线条大小和形状大小?

示例代码:

example <- data.frame(a=c(1,2,3,1,2,3), b=c(0.1,0.2,0.3,0.4,0.5,0.6), c=c('a','a','a','b','b','b'))

ggplot(example, aes(x=a, y=b, color=c, shape=c))+
  geom_line()+
  geom_point()+
  scale_colour_manual(name="title", breaks=c("a","b"),
                      labels=c("label1","label2"),
                      values=c("#e41a1c", "#377eb8"))+
  scale_shape_manual(name="title", breaks=c("a","b"),
                     labels=c("label1","label2"),
                     values=c(15, 16))+
  guides(shape = guide_legend(override.aes = list(size=4)),
         color = guide_legend(override.aes = list(size=1)))

example plot

最佳答案

layer() ggplot 在幕后使用的函数有一个 key_glyph您可以为其提供自定义函数的参数。您可以使用它使点变大,但不能使线条变大。如果需要自定义行调整,可以写一个类似的函数包装draw_key_path() .

library(ggplot2)

example <- data.frame(a=c(1,2,3,1,2,3), b=c(0.1,0.2,0.3,0.4,0.5,0.6), c=c('a','a','a','b','b','b'))

large_points <- function(data, params, size) {
  # Multiply by some number
  data$size <- data$size * 2
  draw_key_point(data = data, params = params, size = size)
}

ggplot(example, aes(x=a, y=b, color=c, shape=c))+
  geom_line()+
  geom_point(key_glyph = large_points)+
  scale_colour_manual(name="title", breaks=c("a","b"),
                      labels=c("label1","label2"),
                      values=c("#e41a1c", "#377eb8"))+
  scale_shape_manual(name="title", breaks=c("a","b"),
                     labels=c("label1","label2"),
                     values=c(15, 16))



创建于 2020-04-08 由 reprex package (v0.3.0)

关于r - 如何独立更改图例中的颜色线条大小和形状大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61096323/

相关文章:

r - 将代码转换为 R 中的函数

python - Stata 与 R/Python 中数据帧的线性代数

r - 在 `geom_hline` 图中设置 `geom_bar` 的长度

r - 使具有许多观察结果的多组线图更具可读性

R Shiny : How do you change the background color of the Header?

返回值的所有可能组合

R - 根据数据框中的条件按组设置值

r - geom_密度用facet_wrap创建扁平线

r - ggplot饼图标签

r - 如何使用矩阵在 ggplot 中生成箱线图