如何在不是来自 R 中的 plot() 的绘图上添加刻度线

How to add tick marks on a plot that is not from plot() in R

我使用 R 包 SetMethods 来获取面板数据的 fsQCA 结果。在包中,它使用 cluster.plot() 函数生成绘图。

但是,我很难让图表的 x 轴将单位数显示为刻度线。例如,我希望它在 x 轴上显示 10、20、30、..、140,以了解有多少单位的一致性分数低于某个点。

有什么方法可以在不是由 plot() 函数生成的绘图上添加刻度线吗?提前致谢。

这里我以包中的数据集为例

install.packages("SetMethods")
library(SetMethods)

data("PAYF")
PS <- minimize(data = PAYF,
               outcome  = "HL",
               conditions = c("HE","GG","AH","HI","HW"),
               incl.cut = 0.9,
               n.cut = 2,
               include = "?",
               details = TRUE, 
               show.cases = TRUE)
PS

# Perform cluster diagnostics:

CB <- cluster(data = PAYF,
              results = PS,
              outcome = "HL",
              unit_id = "COUNTRY",
              cluster_id = "REGION",
              necessity=FALSE,
              wicons = FALSE)
CB

# Plot pooled, between, and within consistencies:

cluster.plot(cluster.res = CB,
             labs = TRUE,
             size = 8,
             angle = 6,
             wicons = TRUE)

最后得到如下图

但是,我希望它在 x 轴上显示 10、20、30、..、140,以了解有多少单位的一致性分数低于某个点。

有什么方法可以在不是由 plot() 函数生成的绘图上添加刻度线吗?提前致谢。

如果您查看 cluster.plot 函数定义(在 RStudio 中,当指针位于其上时按 F2),您会发现它在底层使用了 ggplot2。只是它没有 return ggplot2 对象,只是将它们一个接一个地打印出来。因此,之后不可能以任何方便的方式修改输出。

但是您可以随时复制功能代码并根据自己的需要重写。在你的案例中打印最终情节的部分是

CTw <- list()
ticklabw = unique(as.character(cluster.res$unit_ids))
xtickw <- seq(1, length(ticklabw), by = 1)
if (class(cluster.res) == "clusterminimize") {
  for (i in 1:length(cluster.res$output)) {
    CTw[[i]] <- cluster.res$output[[i]]$WICONS
    dtw <- data.frame(x = xtickw, y = CTw[[i]])
    dtw <- dtw[order(dtw$y), ]
    dtw$xr <- reorder(dtw$x, 1 - dtw$y)
    pw <- ggplot(dtw, aes(y = dtw[, 2], x = dtw[, 
      3])) + geom_point() + ylim(0, 1) + theme_classic(base_size = 16) + 
      geom_hline(yintercept = cluster.res$output[[i]]$POCOS) + 
      labs(title = names(cluster.res$output[i]), 
        x = "Units", y = "Consistency") + theme(axis.text.x = element_blank())
    suppressWarnings(print(pw))
  }
}

可以将ggplot2构造部分修改成这样(需要加载包ggplot2dplyr):

pw <- 
  dtw %>% 
  mutate(x_ind = as.numeric(xr)) %>% 
  ggplot(aes(x_ind, y)) +
  geom_point() +
  ylim(0, 1) +
  theme_classic(base_size = 16) + 
  geom_hline(yintercept = cluster.res$output[[i]]$POCOS) + 
  scale_x_continuous(breaks = seq(from = 0, to = 140, by = 10)) +
  labs(title = names(cluster.res$output[i]),
    x = "Units", y = "Consistency")