繁体   English   中英

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

[英]How can I create this chart in R using ggplot2?

我在 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))

我想创建一个图表(根据上述数据),如下所示(不包括亚马逊徽标)。

我主要是在绘制带有 % 变化的圆圈。

迄今为止,

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完成吗?

亚马逊图表

大多数方式:

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()

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM