gpt4 book ai didi

r - 控制 ggplot 图例中的线型、颜色和标签

转载 作者:行者123 更新时间:2023-12-01 11:19:02 26 4
gpt4 key购买 nike

我在之前还指定了自定义线型和颜色的图上设置自定义图例标签时遇到问题。 stackoverflow 上有一个类似的问题,用于处理 linetypes and line colors 的自定义图例。但是,一旦您希望在上述两个属性之上指定图例标签,ggplot2 似乎开始崩溃。

这是我的最小可重复示例:

library(ggplot2)

df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
treatment = c(rep("one", 2), rep("two", "2")))

ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
geom_line() +
scale_linetype_manual(values = c(1, 3),
labels = c("Treatment one", "Treatment two")) +
scale_color_manual(values = c("black", "red"))

上面的代码产生下图

Setting labels in either scale_linetype_manual or scale_color_manual results in two legends being created.

scale_linetype_manual()scale_color_manual() 中设置标签会导致创建两个单独的图例。具有正确虚线的那条线将始终是无色的。另一方面,具有正确颜色的线型将无法正确表示线型(仅实线)。

有没有办法在 ggplot2 中同时控制颜色、线型和图例标签?或者这是包的限制,我应该在 getgo 的数据框中正确指定标签?

最佳答案

使 scale_linetype_manual() 的标签相同和 scale_color_manual() .

library(ggplot2)

df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2),
treatment = c(rep("one", 2), rep("two", "2")))

ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) +
geom_line() +
scale_linetype_manual(values = c(1, 3),
labels = c("Treatment one", "Treatment two")) +
scale_color_manual(values = c("black", "red"),
labels = c("Treatment one", "Treatment two"))

enter image description here

关于r - 控制 ggplot 图例中的线型、颜色和标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46396292/

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