3

我是 R 新手。我在下图中的geom_text元素排序时遇到问题。geom_col

我相信这与position = position_dodge2(preserve = "single")线路有关,但我不确定。

附上示例代码和输出。如您所见,标签是错误的 -应该切换,e以及和。bad

眼睛更敏锐(可能头脑更敏锐)的人能看出问题所在吗?

在此处输入图像描述

library(ggplot2)
library(stringr)

data <- data.frame(Importance = c("Not important", "Important", "Critical", "Not important", "Important"), Current.Capability = c("Basic", "Undeveloped", "Advanced", "World class", "World class"), Function = c("PM", "Sales", "PM", "Marketing", "Marketing"), Item = c("a","b", "c", "d", "e"))

str(data)
head(data)

width <- 2
position.width <- width - 0.05

ggplot(data, aes(x = Importance, y = Current.Capability, fill=Function)) +
  geom_col(position = position_dodge2(preserve = "single"), width = width) +
  facet_grid(~Importance, scales = "free_x", space = "free_x") +
  geom_text(
    aes(
    label = stringr::str_wrap(Item, 50)), 
    lineheight = 0.7, 
    angle=90, 
    size = 5, 
    hjust=0, 
    vjust=0.5,
    y = 0.5,
    position = position_dodge2(preserve = "single", width = position.width)) +
  theme(axis.text.x = element_blank(), axis.ticks = element_blank()) +
  theme(legend.position="bottom")+ 
  scale_y_discrete(limits = c("Undeveloped", "Basic", "Advanced", "World class")) +
  xlab("Importance") + ylab("Current Capability")
4

1 回答 1

1

不错的作品。也许您可以尝试group = Importance添加geom_text. 也就是说,要“明确定义分组结构”,请参见grouping。另外,这里有一个相关案例。

ggplot(data, aes(x = Importance, y = Current.Capability, fill=Function)) +
  geom_col(position = position_dodge2(preserve = "single"), width = width) +
  facet_grid(~Importance, scales = "free_x", space = "free_x") +
  geom_text(
    aes(
      label = stringr::str_wrap(Item, 50),
      group = Importance), # explicitly define the grouping structure
    lineheight = 0.7, 
    angle=90, 
    size = 5, 
    hjust=0, 
    vjust=0.5,
    y = 0.5,
    position = position_dodge2(preserve = "single", width = position.width)) +
  theme(axis.text.x = element_blank(), axis.ticks = element_blank()) +
  theme(legend.position="bottom")+ 
  scale_y_discrete(limits = c("Undeveloped", "Basic", "Advanced", "World class")) +
  xlab("Importance") + ylab("Current Capability")

在此处输入图像描述

于 2018-12-11T21:55:54.510 回答