gpt4 book ai didi

R 4.0.0 : I am trying to change symbols of legend for a plot in ggplot2, 目前我有重叠的符号

转载 作者:行者123 更新时间:2023-12-04 15:27:32 25 4
gpt4 key购买 nike

我在 ggplot2 中用一条线和一条线段作图,这些符号出现重叠。我可以使用 show.legend 使它们的符号既是箭头又是线,但我想使线段成为箭头,线成为线。在寻找解决方案后,我尝试使用 override.aes 对其进行更改。改变形状似乎没有做任何事情。将线设置为 0 会使该符号的所有内容都消失。

plot image

library(tidyverse)

ggplot(NULL, aes(x=0, y=0)) + geom_point(alpha = 0) +
coord_cartesian(xlim = c(-2.5,2.5),ylim = c(-2.5,2.5)) +
geom_segment(aes(x=0, xend=1, y=0, yend=-2, color ="Vector a"), arrow = arrow(length = unit(0.5, "cm")), show.legend = T) +
geom_abline(aes(intercept=1, slope=1/2, color = "Line 1"), show.legend = T) +
scale_y_continuous(breaks=c(-2:2)) +
scale_x_continuous(breaks=c(-2:2)) +
scale_color_manual(values = c("green", "blue"), guide = guide_legend(override.aes = list(linetype = c(1,1),
shape = c(1,1)))) +
labs(

title = "plot (a) line",
x = "X Axis",
y = "Y Axis"
)

预先感谢您在解决我的问题时提出的任何建议 :)。

编辑:环顾四周,我发现两者的符号都可以通过 key_glyph = draw_key_rect 与其他各种 draw_keys_ 一起工作来改变。它们仍然会同时显示。

最佳答案

试试这个:

library(ggplot2)

ggplot(NULL, aes(x=0, y=0)) + geom_point(alpha = 0) +
coord_cartesian(xlim = c(-2.5,2.5),ylim = c(-2.5,2.5)) +
geom_segment(aes(x=0, xend=1, y=0, yend=-2, linetype ="Vector a"),
colour = "blue",
arrow = arrow(length = unit(0.5, "cm"))) +
geom_abline(aes(intercept=1, slope=1/2, color = "Line 1")) +
scale_y_continuous(breaks=c(-2:2)) +
scale_x_continuous(breaks=c(-2:2)) +
scale_color_manual(values = c("green", "blue")) +
labs(title = "plot (a) line",
x = "X Axis",
y = "Y Axis",
linetype = NULL,
colour = "colour")

评论

在 ggplot 中,您不能轻易地将一种美学用于两个不同的 geom 级别;因此您需要摆弄数据的构建并调用 ggplot 以使用不同的美学来创建您想要的图例。我找不到这方面的明确声明。在 Hadley Wickham (2015) ggplot2 Elegant Graphics for Data Analysis 中指出:

“A legend may need to draw symbols from multiple layers. For example,if you’ve mapped colour to both points and lines, the keys will showboth points and lines.”

"ggplot2 tries to use the fewest number of legends to accurately conveythe aesthetics used in the plot. It does this by combining legendswhere the same variable is mapped to different aesthetics."

这在某种程度上解释了您在情节中遇到的问题。

reprex package 创建于 2020-05-24 (v0.3.0)

关于R 4.0.0 : I am trying to change symbols of legend for a plot in ggplot2, 目前我有重叠的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61982579/

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