在ggplot中组合条形图和散点图

时间:2017-07-25 12:37:36

标签: r ggplot2

我有一个主题的数据,如果客户谈论它是积极的,消极的或中立的,主题影响和与平均值的差异。

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

不幸的是,我完全不知道,我怎么能把这个结合起来,如果它甚至可能的话。 Googeling也没有帮助。你能救我吗?

1 个答案:

答案 0 :(得分:2)

这是一种方法,但它有点像“hacky”。我们使用difference列和share_*列手动定义调用xminxmaxgeom_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')

enter image description here

数据(使用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))