You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot未绘制指定数据问题求助:Browsing与Deciding How to Buy的相关类别数据缺失

排查ggplot客户情感矩阵缺失数据的问题

我仔细看了你的数据和代码,很快找到了问题所在——那些没显示的类别,它们的正负情感总和刚好是0,所以geom_col默认不会绘制高度为0的柱子(毕竟没有视觉高度)。

验证问题

先运行这段代码确认一下这些组合的总和:

df_summary <- df %>% 
  mutate(Journey.Area = factor(Journey.Area, levels = c("Getting Assistance", "Returning", "Using Product", "Installing", "Delivery", "Pickup", "Anticipating", "Buying", "Deciding How to Buy", "Browsing"))) %>% 
  count(Journey.Area, Experience.Framework, wt = Postive.or.Negative, name = "Positive.or.Negative")

# 查看目标组合的情感总和
df_summary %>%
  filter(
    (Journey.Area == "Browsing" & Experience.Framework == "Execution") |
    (Journey.Area == "Deciding How to Buy" & Experience.Framework %in% c("Execution", "Systems"))
  )

输出结果会显示这些组合的Positive.or.Negative值全是0,这就是它们从图表中“消失”的原因。

解决方案

要让这些类别显示出来,我们可以给总和为0的值设置一个极小的偏移(比如±0.01),这样柱子会有一个微小的高度,既不影响整体数据准确性,又能让你看到这些类别存在。修改后的完整代码如下:

library(tidyverse)

df %>% 
  mutate(Journey.Area = factor(Journey.Area, levels = c("Getting Assistance", "Returning", "Using Product", "Installing", "Delivery", "Pickup", "Anticipating", "Buying", "Deciding How to Buy", "Browsing"))) %>% 
  count(Journey.Area, Experience.Framework, wt = Postive.or.Negative, name = "Positive.or.Negative") %>%
  # 给总和为0的类别添加极小偏移,避免重叠
  mutate(Positive.or.Negative = case_when(
    Positive.or.Negative == 0 ~ if_else(Experience.Framework == "Execution", -0.01, 0.01),
    TRUE ~ Positive.or.Negative
  )) %>%
  ggplot(aes(Positive.or.Negative, Journey.Area, fill = Experience.Framework)) + 
  geom_col(position = position_dodge2(preserve = "single")) + 
  geom_vline(xintercept = 0) + 
  theme_light(base_size = 16) + 
  scale_x_continuous(limits = c(-15, 15), labels = abs) + 
  labs(x = 'Negative Sentiment ↔ Positive Sentiment', y="Customer Journey Area", fill="User Experience Framework") + 
  theme(plot.title = element_text(hjust = 0.5)) + 
  theme(axis.title.x = element_text(size = 12)) + 
  ggtitle("Customer Sentiment Matrix") + 
  theme(legend.title = element_text(size = 14))

如果你还想确保所有可能的Journey.Area和Experience.Framework组合都被包含(包括完全没有记录的组合),可以在count之后加上complete函数补全缺失的组合:

... %>%
  count(Journey.Area, Experience.Framework, wt = Postive.or.Negative, name = "Positive.or.Negative") %>%
  # 补全所有组合,缺失的填充为0
  complete(Journey.Area, Experience.Framework, fill = list(Positive.or.Negative = 0)) %>%
  mutate(Positive.or.Negative = case_when(
    Positive.or.Negative == 0 ~ 0.01,
    TRUE ~ Positive.or.Negative
  )) %>%
...

这样调整后,你提到的所有类别都会在图表中显示出来了。

内容的提问来源于stack exchange,提问作者lcarter5

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 21:37:37