如何正确地向ggplot2水平箱线图添加标签

3

我会尽力为您提供翻译,以下是需要翻译的内容:

编辑以提供可重现的示例。

样本数据:https://owncloud.cesnet.cz/index.php/s/oopPE2Ut4quSVOK

有了这些数据

> head(df)
  Sample_Name        E Sentrix_ID Sentrix_ID_full
1    P129C1S1 5.636927 5058818037    5058818037_A
2    P129C1S1 5.794948 5058818037    5058818037_A
3    P129C1S1 5.608488 5058818037    5058818037_A
4    P129C1S1 5.989108 5058818037    5058818037_A
5    P129C1S1 5.570090 5058818037    5058818037_A
6    P129C1S1 5.555401 5058818037    5058818037_A

我正在生成水平箱线图。
library(ggplot2)
library(ggthemes)

df <- read.csv("sample.csv")
df$Sentrix_ID <- as.factor(df$Sentrix_ID)
df$Sentrix_ID_full <- as.factor(df$Sentrix_ID_full)

head(df)

p <- ggplot(data = df,
            aes(y = E, x = Sentrix_ID_full, color = Sentrix_ID, label = Sample_Name)) +
  geom_boxplot(outlier.shape = NA) +
  scale_colour_manual(values = c("5058818037" = "red", "5226121006" = "green")) +
  theme_few() +
  guides(colour = FALSE) +
  labs(x = "Sentrix ID", y = "E", title = "intensity values") +
  coord_flip()

p

我想给每个箱线图添加标签:

p <- p + geom_text()

但是会出现这种情况:

有解决方案吗?谢谢提前


对于这种问题,我大多使用ggrepel()包中的geom_text_repel()函数。不幸的是,我不确定它是否适用于您的问题。 - Koot6133
geom_text() 中的 label 是什么意思? - pogibas
@Koot6133 谢谢,我会尝试一下。但是似乎每个标签都被渲染了多次(你可以看到沿着箱线图的一些字母)。 - jirinovo
@PoGibas 我不明白你的意思。 - jirinovo
请展示您使用 geom_text(第二个图)的代码。 - pogibas
显示剩余3条评论
1个回答

5
一些建议:使用第二个数据框仅一次标记每个箱形图,并在定义的位置上进行标记。
# mock data
set.seed(1)
df <- data.frame(var_1 = c(rep("A", 15), rep("B", 15), rep("C", 15)),
             value = sample(100, 45, replace= T))

# the kind of plot you have
ggplot(df, aes(x = var_1, y = value, label = var_1)) +
  geom_boxplot() +
  coord_flip() +
  geom_text()

plot_1

# Use of plyr package
library(plyr)
df2 <- ddply(df, "var_1", summarize, max_value = max(value, na.rm = T))
# I chose max_value as position for the label

# the new plot
ggplot(df, aes(x = var_1, y = value)) +
  geom_boxplot() +
  coord_flip() +
  geom_text(data = df2, aes(x = var_1, y = max_value, label = var_1), hjust = -0.5) # use hjust to adjust horizontal position 

enter image description here


谢谢,运行良好 :) 我刚刚使用了第三四分位数(quantile(E, probs = c(0.75), na.rm = T))代替了最大值。标签位置是通过nudge_y = 1进行调整而不是hjust。结果:https://ctrlv.cz/shots/2017/12/04/Uka6.png - jirinovo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接