繁体   English   中英

向 ggplot(加权)小提琴图添加独立标签

[英]Add independent labels to ggplot (weighted) violin plot

我正在尝试为 ggplot 加权小提琴图中的每个因素添加一组额外的解释性标签。 在下面的虚拟示例中,我希望数据框“LBLS”中的“额外”字段在 y 值 2 处绘制标签,该标签位于每个小提琴下方。 这种尝试没有奏效,因为我不了解 ggplot 的工作方式(还)。

require(ggplot2)
LBLS <- data.frame(c("Species A", "Species B","Species C"))
names(LBLS) <- "Extra"

ggplot(data = iris, aes_string(x = names(iris)[5], y = names(iris)[2], fill = names(iris)[5] ), weight = names(iris)[4]) +             # data and weight
  geom_violin(show.legend = FALSE) +
  ggtitle("Weighted violin plots") +
  geom_label(x = names(iris)[5], y = 2,  label = LBLS$Extra)

有一些语法改进可能会使事情变得更清楚。 但主要问题是,如果您希望“物种 A”成为“setosa”上的标签,则需要将这两个值关联在一起。 有几种方法可以做到这一点。 这是将lbls数据框与iris连接lbls的一个,然后绘制:

lbls <- tibble(Extra = c("Species A", "Species B", "Species C"),
               Species = c("setosa", "versicolor", "virginica"))

iris %>% 
  left_join(lbls, by = "Species") %>% 
  ggplot(aes(x = Species, y = Sepal.Width, weight = Petal.Width)) +           
  geom_violin(aes(fill = Species), show.legend = FALSE) +
  geom_label(aes(label = Extra), y = 2) +
  labs(title = "Weighted violin plots")

在此处输入图片说明

这是另一种避免连接的方法。 将“Species [X]”值映射到iris$Species值,然后使用该映射向iris添加一列:

lbls2 <- list(setosa = "Species A", 
              versicolor = "Species B", 
              virginica = "Species C")

iris %>% 
  mutate(extra = lbls2[Species]) %>%
  ggplot(aes(x = Species, y = Sepal.Width, weight = Petal.Width)) +           
  geom_violin(aes(fill = Species), show.legend = FALSE) +
  geom_label(aes(label = extra), y = 2) +
  labs(title = "Weighted violin plots")

暂无
暂无

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

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