从 Lattice 包 R 更改点图中 x 轴标签的颜色

Change colors of x-axis labels in dotplot from Lattice package R

我想知道是否有办法更改我使用 R 中的 lattice 包创建的点图上某些 x 轴标签的颜色。

这是我的例子 data/code:

State <- factor(c("AZ", "AR", "NJ"))
Value <- c(1.2, 4.5, 2.0, 1.5, 4.0, 1.4)
Year <- c(2000, 2000, 2000, 2005, 2005, 2005)

p <- dotplot(Value ~ State, groups = Year, main = "Test Data",
        xlab = "State/Territory", ylab = "Data", auto.key = TRUE)

我想把AZ和AR放在一起(x轴是同色文字,我们可以做成蓝色)

我希望NJ有自己的组(x轴文字颜色不同,我们可以做成粉红色)

我可以在图表中画一条垂直线以更好地分隔组吗?

感谢您的帮助!

可以看出,在遗留绘图系统上控制它非常复杂 。一种方法可能是使用像 ggplot2 这样的现代绘图系统。

library(ggplot2)
data <- data.frame(State = factor(c("AZ", "AR", "NJ")),Value = c(1.2, 4.5, 2.0, 1.5, 4.0, 1.4), Year = c(2000, 2000, 2000, 2005, 2005, 2005))

ggplot(data,aes(x=State,y=Value,color = State, shape = as.factor(Year))) + 
  geom_point(size = 3) + scale_color_manual(values=c("blue","blue","pink")) + scale_shape_discrete(name = "Year") +
  theme(axis.text.x = element_text(colour = c("blue","blue","pink")), plot.title = element_text(hjust = 0.5)) +
  geom_vline(xintercept = 2.5) + labs(title = "Test Data", x = "State/Territory", y = "Data") 

好吧,只是为了好玩,有时 lattice 并没有那么复杂,而且它在做一些大量的绘图时仍然非常快。

在你的情况下,你需要指定组为State,然后使用col指定3种颜色,并在面板函数中执行panel.abline,例如:

dotplot(Value ~ State, groups=State,
main = "Test Data",
col=c("blue","blue","brown"),
panel = function(x, y,...) {
         panel.dotplot(x, y,levels.fos = unique(x),...)
         panel.abline(v=2.5)
       })

当然,一个缺点是您不能轻易指定另一个组变量,例如此处的年份。

# This could be a solution with lattice

dotplot(Value ~ State, data, groups = State,
        scales = list(x = list(col = ifelse(levels(data$State) %in% c("AZ", "AR"), "blue", "deeppink2"))),
        par.settings = list(superpose.symbol = list(col = c("blue", "blue", "deeppink2"), pch = 16)),
        panel = function(...) {
          panel.abline(v = 2.5)
          panel.dotplot(...)
        })