标签重叠有问题(geom_text)

时间:2019-06-11 09:42:38

标签: r ggplot2 pie-chart

饼图上的geom_text标签重叠的问题

library(scales)
blank_theme <- theme_minimal()+
theme(
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    panel.border = element_blank(),
    panel.grid=element_blank(),
    axis.ticks = element_blank(),
    plot.title=element_text(size=14, face="bold")
)


df6 <- data.frame(group = c("Seedling","Ground", "Fern", "Moss"),value = c(2.125,80.125, 11.376,6.375))
# Create a basic bar
pie6 = ggplot(df6, aes(x="", y=value, fill=group)) + geom_bar(stat="identity", width=1) + blank_theme + theme(axis.text.x=element_blank())

# Convert to pie (polar coordinates) and add labels
pie6 = pie6 + coord_polar("y", start=0) + geom_text(aes( label = paste0((value), "%")),position = position_stack(vjust = 0.5))


# Remove labels and add title
pie6 = pie6 + labs(x = NULL, y = NULL, fill = NULL, title = "Understory Composition, Site 2")

# Tidy up the theme
pie6 = pie6 + theme_classic() + theme(axis.line = element_blank(),
                                  axis.text = element_blank(),
                                  axis.ticks = element_blank(),
                                  plot.title = element_text(hjust = 0.5, color = "black"))

pie6

enter image description here

这是我当前的输出。如何更改标签以使其不重叠?我尝试过各种调整和调整,positions和position_stack,但无济于事

任何帮助表示赞赏。谢谢。

2 个答案:

答案 0 :(得分:0)

您是否尝试过使用ggrepel软件包?如果是这样,我建议。它会自动停止标签重叠并找到彼此适合的标签。

private void ScanQrcode() {
zXingScannerView = new ZXingScannerView(this);
zXingScannerView.setResultHandler((ZXingScannerView.ResultHandler)context);
zXingScannerView.startCamera();
setContentView( zXingScannerView );

}

答案 1 :(得分:0)

解决此问题的一种手动方法可能是通过在angle函数中设置geom_text参数来操纵文本的方向。这样,您可以通过将singel值分配给angle来一次设置所有文本片段的方向。您还可以如下图所示为各个文本项设置角度。

ggplot(df6, aes(x = "", y = value, fill = group)) + 
  geom_bar(stat = "identity", width = 1) + 
  coord_polar("y", start = 0) + 
  blank_theme +
  theme(axis.text.x = element_blank()) +
  geom_text(aes(label = paste0((value), "%")), 
            position = position_stack(vjust = 0.5), 
            angle = c(-90, -90, 0, -90))              ####### here

enter image description here

下面的代码根据其描述的饼图来调整角度。

ggplot(df6, aes(x = "", y = value, fill = group)) + 
  geom_bar(stat = "identity", width = 1) + 
  coord_polar("y", start = 0) + 
  blank_theme +
  theme(axis.text.x = element_blank()) +
  geom_text(aes(label = paste0((value), "%")), 
            position = position_stack(vjust = 0.5), 
            angle = c(-97, -110, 0, -70))             ####### here

enter image description here

解决您所陈述的问题的另一种方法是,使用start函数的coord_polar参数:

ggplot(df6, aes(x = "", y = value, fill = group)) + 
  geom_bar(stat = "identity", width = 1) + 
  coord_polar("y", start = 180) +               ####### here
  blank_theme +
  theme(axis.text.x = element_blank()) +
  geom_text(aes(label = paste0((value), "%")) , 
            position = position_stack(vjust = 0.5))

enter image description here