R语言 将地块上的标签移离直线

xuo3flqw  于 2023-02-10  发布在  其他
关注(0)|答案(2)|浏览(164)

我有一个像这样的数据框

TEST1 <- data.frame(
    Number = c(46.68, 46.45, 48.35, 44.63, 45.65, 46.46, 45.14, 45.69, 47.10),
    House.Height= c("LOW", "LOW", "LOW", "MODERATE", "MODERATE", "MODERATE", "HIGH", "HIGH", "HIGH"))

我已经使用以下代码创建了箱线图:

ggboxplot(TEST1, x = "House.Height", y = "Number", fill = "House.Height", palette = c("#009E73", "#D55E00", "#CC79A7"), order = c("LOW", "MODERATE", "HIGH"), sort.by.groups = TRUE,
          label = TRUE, label.pos = "out", lab.vjust = -2
) +
    scale_x_discrete(labels = c("low", "moderate", "high")) +
    xlab("House Height")+ ylab("Number") + 
    labs(fill = "House"
    ) + 
    scale_y_continuous(breaks = seq(44,50)) +
    coord_cartesian(ylim = c(44, 50))

但是,我可以从结果中看到,“LOW”条中的一个标签(46.45)在线上,您可以看到大麦44.63和45.14中的点。

有没有办法把它们向下移动,这样它们就能更明显了,我以为vjust会有,但很明显,它没有,我也试过为yaxis使用各种刻度,没有任何成功,任何帮助都将不胜感激。

brjng4g3

brjng4g31#

您可以使用repel=TRUE选项吗?

或者,您可以将ggplotgeom_label_repel一起使用,以获得更好的结果:

ggplot(TEST1 , aes(x=House.Height, y=Number, fill=House.Height)) + geom_boxplot() + theme_bw() + 
  scale_fill_manual(values = c("#009E73", "#D55E00", "#CC79A7")) + 
  theme_bw()  +
  theme(legend.position = "top") + 
  scale_x_discrete(limits=c("LOW", "MODERATE", "HIGH")) + 
  geom_point() + 
  ggrepel::geom_label_repel(aes(label=Number), force=1.5, fill=hsv(0,0,1,alpha=0.5))

63lcw9qa

63lcw9qa2#

我认为在ggplot中使用geom_boxplot会更容易实现这一点,因为这样您就可以简单地使用geom_text,而使用nudge_x和nudge_y进行调整非常简单。我还在绘图前重新排列了因子水平,并将调色板置于scale_fill_manual中。

TEST1$House.Height <- factor(TEST1$House.Height, levels = c('LOW', 'MODERATE', 'HIGH'))

ggplot(TEST1, aes(x = House.Height, y = Number))+
  geom_boxplot(aes(fill = House.Height)) +
  scale_x_discrete(labels = c("low", "moderate", "high")) +
  xlab("House Height")+ ylab("Number") + 
  labs(fill = "House") + 
  scale_y_continuous(breaks = seq(44,50)) +
  coord_cartesian(ylim = c(44, 50)) +
  scale_fill_manual(values = c("#009E73", "#D55E00", "#CC79A7")) +
  geom_text(aes(label = Number, x = House.Height, y = Number), nudge_x = 0.5, size = 3) +
  theme_classic() +
  theme(legend.position = 'top')

相关问题