【问题标题】:geom_col values out of ordergeom_col 值乱序
【发布时间】:2018-12-11 19:30:56
【问题描述】:

我是 R 新手。我在下面的geom_col 图表中对geom_text 元素的排序有问题。

我认为这与position = position_dodge2(preserve = "single") 行有关,但我不确定。

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

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

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")

【问题讨论】:

    标签: r ggplot2 position geom-text geom-col


    【解决方案1】:

    干得好。或许你可以尝试在geom_text的美学中加入group = Importance。也就是说,要“明确定义分组结构”,请参阅grouping。另外,here 是一个相关案例。

    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")
    

    【讨论】:

    • 谢谢!这个问题确实与分组有关。我通过包含在 geom_col 的 aes 中解决了它,但是,不是 geom_text。但你让我走上了正轨!
    • 嗨@BrevanD'Angelo!凉爽的!您也可以将group = Importance 直接包含在ggplotaes 中,例如ggplot(data, aes(..., group = Importance)),也可以使用。
    猜你喜欢
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2016-07-05
    • 2012-01-27
    • 2021-06-06
    相关资源
    最近更新 更多