如何使用ggplot2在R中创建此图表?

时间:2019-08-22 17:08:27

标签: r ggplot2 charts

我在RStudio中使用R,并且具有以下数据框。

df1 <- data.frame(  
  comp = c("A", "B", "C", "D", "E", "F"),  
  Q2_2018 = c(27, 10, 6, 4, 3, 2),  
  Q2_2019 = c(31, 12, 8, 6, 5, 4))

我想根据上面的数据创建一个图表,如下所示(不包括Amazon徽标)。

我主要停留在绘制具有%变化的圆圈。

到目前为止,

library(ggplot2)
library(reshape2)
library(magrittr)

melt(df1, id.vars = "comp") %>% 
  ggplot(aes(x= comp, y=value, fill=variable)) + geom_bar(stat = "identity", position = "dodge")

可以用ggplot2完成吗?

amazon chart

1 个答案:

答案 0 :(得分:1)

大部分方式:

library(tidyverse)
df1 %>%
  gather(year, val, -comp) %>%
  group_by(comp) %>% 
    mutate(change = val / lag(val) - 1) %>%
    mutate(change_lab = if_else(!is.na(change),
                                scales::percent(change, 
                                        accuracy = 1, 
                                        prefix = if_else(change > 0, "+", "-")),
                                NA_character_)) %>% 
  ungroup() %>%

  ggplot(aes(comp, val, fill = year, label = val)) +
  geom_col(position = position_dodge()) +
  geom_text(position = position_dodge(width = 1), vjust = -0.5) +
  geom_point(aes(comp, val + 5, size = change), color = "lightgreen") +
  geom_text(aes(comp, val+5, label = change_lab)) +
  scale_size_area(max_size = 30) +
  guides(size= F) +
  theme_classic()

enter image description here