简体   繁体   English

如何使用晶格将更新的线条颜色合并到R中的图形的图例中?

[英]How to incorporate updated line colours into legend of a plot in R using lattice?

Context and Question: 背景和问题:

I want to add a legend to a lattice plot in R that shows the density of two groups. 我想在R中的格子图中添加一个图例,显示两组的密度。 I've changed the default colours to black and gray. 我已将默认颜色更改为黑色和灰色。 However, the legend has not updated the colours. 但是,图例没有更新颜色。

  • How can I get the lattice plot to use my updated colours in the legend? 如何让格子图在图例中使用我更新的颜色?
  • How can I control the position of the legend (I'd like to be able to place it inside the plot area)? 如何控制图例的位置(我希望能够将其放置在绘图区域内)?

Working example: 工作范例:

set.seed(4444)
x1 <- rep("Group A", 50)
x2 <- rep("Group B", 50)
y1 <- rnorm(50, 0, 2)
y2 <- rnorm(50, 1, 2)
dtf <- data.frame(x=c(x1, x2), y =c(y1, y2))

print(densityplot(~y, groups=x, data=dtf,
    pch=".",
    cex=2,
    col=c("black", "gray"),
    auto.key=TRUE,
    xlab="Y"))

在此输入图像描述

The legend color is a well-known annoyance in lattice. 传奇色彩是格子中众所周知的烦恼。 It looks like it is difficult to correct, because Deepayan recommends simpleTheme as a solution. 看起来很难纠正,因为Deepayan建议使用simpleTheme作为解决方案。 For positioning, see Josh's answer. 有关定位,请参阅Josh的回答。

print(densityplot(~y, groups=x, data=dtf,
              pch=".",
              cex=2,
              par.settings=simpleTheme(col=c("gray","black")),
              auto.key=TRUE,
              xlab="Y"))

There might be a more elegant solution, but this works well enough. 可能有一个更优雅的解决方案,但这很好用。 Notice that the corner= argument can be used to place the legend anywhere inside the plot. 请注意, corner=参数可用于将图例放置在图中的任何位置。

densityplot(~y, groups = x, data = dtf,
    pch = ".",
    cex = 2,
    col = c("black", "gray"),
    par.settings = list(superpose.line = list(col=c("black", "grey"))),
    auto.key = list(corner = c(0.95, 0.95)),
    xlab = "Y")

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM