[英]combine bar and scatterplot in ggplot
我有一個主題的數據,如果客戶談論積極,消極或中立,主題影響和平均差異。
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的例子):
不幸的是,我完全不知道,我怎么能把這個結合起來,如果它甚至可能的話。 Googeling也沒有幫助。 你能幫助我嗎?
這是一種方法,但它有點“hacky”。 我們使用difference
列和share_*
列手動定義調用geom_rect
時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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.