我有一个主题的数据,如果客户谈论它是积极的、消极的或中立的,以及这些主题的影响和与平均水平的差异。
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 的例子):
不幸的是,我完全不知道如何将其结合起来,甚至可能的话。谷歌搜索也无济于事。你能帮助我吗?
最佳答案
这是一种方法,但它有点“hacky”。当我们调用 difference
时,我们使用 share_*
列和 xmin
列手动定义 xmax
和 geom_rect
应该在哪里。为了确保我们真的得到了一个酒吧,我们在 ymax
中添加了一些软糖因子 (0.1)
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))
关于r - 在ggplot中结合条形图和散点图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45303537/