gpt4 book ai didi

r - 自动为 r 中的图形生成图例?

转载 作者:行者123 更新时间:2023-12-02 22:24:17 25 4
gpt4 key购买 nike

是否有可能在 R 中自动生成图例?真正让我烦恼的一件事是冗余信息,我必须输入这些信息才能显示图例(例如线条颜色,...)

plot(
c(1:5), c(.7, 2.2, 3.1, 3.9, 5.2),
col=1,
pch=3,
type="b"
)

lines(
c(1:5), c(1:5),
col=2,
pch=6,
type="o"
)

legend(
"topleft",
legend=c("data", "expactation"),
col=c(1, 2),
pch=c(3, 6),
lty=c(2 ,1)
)

我已经在命令 plotlines 中提供了有关线条颜色的信息...。如果我不必在图例中再次添加此信息,那就太好了。

例如,是否可以将“线”对象和“绘图”对象存储在一个变量中,并且只将这些对象传递给图例(图例在其中找到所需信息)?

p = plot(...)
l = lines (...)
legend("topleft", p, l)

最佳答案

Is it for example possible to store the "lines"-Object and "plot"-object in a variable and only pass these objects to legend (where legend finds the required information)

不容易。但是,ggplot2 为您提供了此功能。例如,

##Create some data and load the library
dd = data.frame(x = c(1:5,1:5), y = c(.7, 2.2, 3.1, 3.9, 5.2, 1:5),
type=rep(c("data", "expectation"), each=5))

require(ggplot2)

接下来我们创建一个plot对象`:

##Legend is automatically generated
g = ggplot(data=dd, aes(x = x, y=y)) +
geom_point(aes(colour=type, pch=type))
g

不是我们向“绘图对象”添加一些行:

g + geom_line(aes(colour=type, pch=type))

关于r - 自动为 r 中的图形生成图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13192535/

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