如何防止标签在 R (ggplot) 的堆积条形图中出现混乱?

问题描述 投票:0回答:1

我一直在尝试解决这些百分比标签被抛出图像之外并且当数字太低时无法正确显示的问题,但似乎找不到解决方案。

您可以在图像的右侧看到它,替代方案 C 和 D 通常会被推到一起,并且您无法读取 geom_text 标签中的百分比。

我的 df“bloco”由以下列组成: -项目:调查问卷项目,例如一个问题 -替代方案:相应项目的每个替代方案 -p:该项目中该替代方案的答案百分比 -区块:该项目属于哪个区块

bloco %>%
  ggplot(aes(y = as.factor(Item), x = p, fill = Alternative, group = Block)) +
  geom_text(
    aes(y = as.factor(Item), x = p, label = p),
    # position = position_dodge(width = 1),
    size = 2.5
  ) +
  geom_bar(stat = "identity") +
  geom_text(
    aes(label = p),
    position = position_stack(vjust = 0.5),
    size = 3,
    color = "#413F1A"
    # nudge_x = -1,
    # hjust= 1
  ) +
  scale_fill_manual(
    name = ''
    , values = c(
      '(A) Nunca ou quase nunca.' = '#F9E79F',
      '(B) De vez em quando.' = '#F7DC6F',
      '(C) Quase sempre.' = '#F4D03F',
      "(D) Sempre." = "#F1C40F"
    )
  ) +
  scale_y_discrete(labels = label_wrap_gen(25))+
  scale_x_continuous(labels = scales::percent_format(scale = 100), limits = c(0, 1.02)
                     )+
  labs(#title = paste0("Gráfico ", ngraf,  ": Percepção dos professores sobre a segurança no contexto escolar."), 
    x = "Frequência de Respostas (%)", y = "") +
  theme_test() +
  theme(plot.title = element_text(size = 11)
        , legend.key.size = unit(0.3, 'cm')
        , legend.position = 'bottom')

My answer pattern chart

我已经尝试过 vjust 并手动定位它们,但它也不起作用。

r ggplot2 graph visualization
1个回答
0
投票

我们没有您的数据,因此我们需要创建类似的东西来演示问题和解决方案:

library(ggplot2)

df <- data.frame(category = rep(letters[1:5], each = 5),
                 response = rep(LETTERS[1:5], 5), 
                 vals = c(0.1, 0.2, 0.3, 0.35, 0.05,
                          0.01, 0.01, 0.08, 0.8, 0.1,
                          0.01, 0.1, 0.19, 0.68, 0.02,
                          0.2, 0.2, 0.2, 0.2, 0.2,
                          0.01, 0.02, 0.87, 0.08, 0.02))

ggplot(df, aes(vals, category, fill = response)) +
  geom_col() +
  geom_text(aes(label = scales::percent(vals, 0.1)),
            position = position_stack(vjust = 0.5)) +
  scale_fill_manual(NULL, values = c('#F9E79F', '#F7DC6F', '#F5D853',
                                     '#F4D03F', "#F1C40F")) +
  theme_classic()

解决此问题的典型方法(假设您不想选择不同类型的绘图)是使用

geom_text_repel
:

library(ggrepel)

ggplot(df, aes(vals, category, fill = response)) +
  geom_col() +
  geom_text_repel(aes(label = scales::percent(vals, 0.1)),
            position = position_stack(vjust = 0.5), direction = 'y') +
  scale_fill_manual(NULL, values = c('#F9E79F', '#F7DC6F', '#F5D853',
                                     '#F4D03F', "#F1C40F")) +
  theme_classic()

© www.soinside.com 2019 - 2024. All rights reserved.