【问题标题】:Changing the font in my ggplot dendrogram更改我的 ggplot 树状图中的字体
【发布时间】:2021-11-12 16:38:43
【问题描述】:

我尝试绘制一个彩色的树状图以包含在我的论文中,除了一件事:更改字体之外,一切都很好。我之前绘制了许多树状图,更改字体从来都不是问题,但在这段代码中它突然是......我可能试图在任何可能的空间中写 family="serif",但 idoes 不起作用。我的代码:

dencw3m <- as.dendrogram(aggl.clust.manhattan.ward.cw3m)

dendro.col.cw3m <- dencw3m %>%
  set("branches_k_color", k = 5, value =   c("blue", "red", "limegreen", "gold", "darkorange")) %>%
  set("branches_lwd", 0.6) %>%
  set("labels_colors", 
      value = c("darkslategray")) %>% 
  set("labels_cex", 0.5)

gg.cw3m <- as.ggdend(dendro.col.cw3m)

ggplot(gg.cw3m, theme = theme_minimal()) +
  labs(x = "Fall", y = "Homogenität", title = "Dendrogramm cw3m", family = "serif", cex = 0.4, hang = -1)

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。明确列出您正在使用的所有非基础 R 包。
  • 您可以通过grSoftVersion() 获得哪些选项,并发布结果和操作系统,R 版本,将使帮助变得更容易。

标签: r ggplot2 fonts cluster-analysis dendrogram


【解决方案1】:

我不熟悉dendextend 包,因此不确定它是否提供了通过参数设置字体系列的简单选项。但是,由于最终结果是ggplot 对象,因此实现所需结果的一种方法是手动设置用于添加标签的geom_text 层的family 参数。

使用来自?ggdend的默认示例:

library(dendextend)
library(ggplot2)

dend <- iris[1:30, -5] %>%
  dist() %>%
  hclust() %>%
  as.dendrogram() %>%
  set("branches_k_color", k = 5, value =   c("blue", "red", "limegreen", "gold", "darkorange")) %>%
  set("branches_lwd", 0.6) %>%
  set("labels_colors", 
      value = c("darkslategray")) %>% 
  set("labels_cex", 0.5)

ggd1 <- as.ggdend(dend, theme = theme_minimal())

p <- ggplot(ggd1)

查看p 的层我们看到geom_text 是第三层:

p$layers
#> [[1]]
#> mapping: xend = ~xend, yend = ~yend, colour = ~col, linetype = ~lty, size = ~lwd, x = ~x, y = ~y 
#> geom_segment: arrow = NULL, arrow.fill = NULL, lineend = square, linejoin = round, na.rm = TRUE
#> stat_identity: na.rm = TRUE
#> position_identity 
#> 
#> [[2]]
#> mapping: colour = ~col, shape = ~pch, size = ~cex, x = ~x, y = ~y 
#> geom_point: na.rm = TRUE
#> stat_identity: na.rm = TRUE
#> position_identity 
#> 
#> [[3]]
#> mapping: label = ~label, colour = ~col, size = ~cex, x = ~x, y = ~y 
#> geom_text: parse = FALSE, check_overlap = FALSE, na.rm = FALSE
#> stat_identity: na.rm = FALSE
#> position_identity

因此,要切换字体系列,我们可以像这样设置该层的aes_paramsfamily 参数:

p$layers[[3]]$aes_params$family <- "serif"
p

【讨论】:

    猜你喜欢
    • 2020-01-19
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    相关资源
    最近更新 更多