为多面水平geom_bar(facet_share、facet_wrap)添加x轴上的条间距

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

我正在尝试在水平条形图中添加间距。如果我只需要使用一个构面组,我可以使用 facet_share 来完成此操作,但在这种情况下,我使用两个变量进行构面。我想在 x 轴中心周围添加空间,以便能够正确可视化垂直文本(E、F、D 等)。

这是我的代码:

Q9 <- c("A", "B", "A", "B","A", "B","A", "B")
Region <- c("Asia", "Europe", "America","Asia", "Europe", "America","Asia", "Europe")
Country <- c("D", "E", "F", "G", "D", "E", "F", "F")

d <- data.frame(Q9, Region, Country)

yn_try <- d %>%
  group_by(Q9, Region, Country) %>%
  summarise(perc = n()) %>%
  group_by(Country, Region) %>%
  mutate(n = perc, perc = perc/sum(perc)*100) %>%
  mutate(perc = case_when(Q9 == "A" ~ perc*-1, TRUE ~ perc)) %>%
  ungroup() %>%
  ggplot(aes(x = reorder(Country, perc), y = perc, fill = Q9)) +
  geom_bar(stat = "identity", show.legend = FALSE, color = "black") +
  labs(x = "", y = "Percentage (%)", title = "TITLE") +
  facet_wrap(~Region, scales = "free") +
  coord_flip() +
  geom_text(aes(label = Country), y = 0, vjust = 0.5, hjust = 0.5, size = 3) +
  theme_classic() +
  theme(plot.title = element_text(face = "bold.italic", size = 10),
        strip.background = element_blank(),
        strip.text = element_text(size = 12, face = "bold"),
        text = element_text(size = 12),
        axis.text.y = element_blank(), # Remove y-axis text
        axis.ticks.y = element_blank()) # Remove y-axis ticks

yn_try

这就是我得到的

enter image description here

理想情况下,我期望像使用facet_share一样的输出,但这似乎不起作用。结果应该是中心的国家/地区组,左右条之间有空格,以便清楚地阅读文本。

r ggplot2
1个回答
0
投票

如果我需要蝴蝶图,并且我不能使用构面,我可能会这样做:

library(ggplot2)

# make a simple butterfly chart by shifting x values and breaks by offset
# fake data

df <- data.frame(
  country = c("France", "Germany", "Italy"), 
  value = c(10, -6, 3)
)

offset = 2
p <- ggplot(df)+
  geom_segment(
    aes(
    x = sign(value) * offset, 
    xend = sign(value) * (abs(value)+offset), 
    y = reorder(country, value), 
    yend = reorder(country, value),
    color = as.factor(sign(value))
    ),
    linewidth = 10)+
  geom_text(aes(x = 0, y = reorder(country, value), label = country), hjust = 0.5, vjust = 0.5)+
  scale_color_manual(values = c("#ef6f00", "#2f8fff"))
# this is not yet working, the labels are not aligned with the bars
p

# define the breaks and labels
labels <- c(-10, -5, -0, 0, 5, 10)
breaks <- (abs(labels) + offset)* rep(c(-1, 1), each = length(labels)/2)
limits = range(breaks)

# add the offset to the x-axis
p +
  scale_x_continuous(labels = labels,
                     breaks = breaks,
                     limits = limits
                     )
© www.soinside.com 2019 - 2024. All rights reserved.