在ggplot中结合柱状图和散点图

3

我有一个关于话题的数据,如果客户对它表达了积极、消极或中立的态度,以及这个话题的影响和与平均值的差异。

data <- data.frame(topic = c("a", "b", "c", "d"), impact = runif(4, min = -2, max = 2), 
               difference = runif(4, min = -30, max = 30),n = round(runif(4, min = 1, max = 100)), 
               share_positive = c(0.04, 0.9, 0.3, 0.37), share_neutral = c(0.7, 0.06, 0.48, 0.4), 
               share_negative = c(0.26, 0.04, 0.22, 0.23))

我把它放在一个简单的散点图中:
ggplot(data = data, aes(x = difference, y = impact, size = n, label = topic)) +
  geom_point() +
  geom_text(size = 4, vjust = -1, colour = "black")

然后我添加了颜色来区分积极和不太积极的主题:

ggplot(data = data, aes(x = difference, y = impact, size = n, label = topic, colour = share_positive)) +
  geom_point() +
  scale_color_continuous(low = "grey", high = "green", guide = FALSE) +
  geom_text(size = 4, vjust = -1, colour = "black")

不要使用颜色,最好使用条形图来表示此主题中负面、中性和正面反馈的占比。我的想法是这样的(以b和d为例):

enter image description here

不幸的是,我完全不知道如何将它们组合起来,也不知道是否可能。谷歌搜索也没有帮助。你能帮我吗?


我看到一种方法,但可能不是最简单的:手动计算您的框的角落并使用geom_rect... - abichat
1个回答

2
这里有一种方法可以做到,但它有点“hacky”。我们使用difference列和share_*列手动定义在调用geom_rect时应该是xminxmax。为了确保我们真正获得一个柱形图,我们将一个小的调整因子(0.1)添加到ymax中。
library(tidyverse)
theme_set(theme_bw())

data %>%
    mutate(neg_left = difference - share_negative,
           neutral_right = difference + share_neutral,
           positive_right = neutral_right + share_positive) %>%
    ggplot(., aes(ymin = impact, ymax = impact + .1))+
    geom_text(aes(x = difference, y = impact, label = topic), vjust = 1)+
    geom_rect(aes(xmin = neg_left, xmax = difference), fill = 'red', colour = 'black')+
    geom_rect(aes(xmin = difference, xmax = neutral_right), fill = 'grey', colour = 'black')+
    geom_rect(aes(xmin = neutral_right, xmax = positive_right), fill = 'green', colour = 'black')

在此输入图片描述

数据(使用set.seed以实现可重复性)

set.seed(456)
data <- data.frame(topic = c("a", "b", "c", "d"), impact = runif(4, min = -2, max = 2), 
                   difference = runif(4, min = -30, max = 30),n = round(runif(4, min = 1, max = 100)), 
                   share_positive = c(0.04, 0.9, 0.3, 0.37), share_neutral = c(0.7, 0.06, 0.48, 0.4), 
                   share_negative = c(0.26, 0.04, 0.22, 0.23))

太棒了!非常感谢 @bouncyball - nelakell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接