堆积条形图复制

时间:2018-12-07 10:32:48

标签: r ggplot2

我正在尝试创建一个堆积的条形图,类似于下面的图。我的数据略有不同。

stacked bar plot

这是我的尝试(失败),因为我无法将公司名称设置为与应该显示时间的颜色相对应(在x轴上有颜色)。

library(reshape2)
dat2 <- melt(df, id.vars = "X__1")
library(ggplot2)
ggplot(dat2, aes(x = variable, y = value, fill = X__1)) + 
  geom_bar(stat = "identity") +
  guides(fill = FALSE) +
  theme_bw()

数据:

df <- structure(list(X__1 = c("1Q '16", "2Q '16", "3Q '16", "4Q '16", 
"1Q '17", "2Q '17", "3Q '17", "4Q '17", "1Q '18", "2Q '18", "3Q '18"
), Samsung = c(81.19, 76.74, 71.73, 76.78, 78.77, 82.86, 85.61, 
74.03, 78.56, 72.34, 73.36), Apple = c(51.63, 44.4, 43, 77.04, 
51.99, 44.31, 45.44, 73.18, 54.06, 44.72, 45.75), Huawei = c(28.86, 
30.67, 32.49, 40.8, 34.18, 35.96, 36.5, 43.89, 40.43, 49.85, 
52.22), Xiaomi = c("-", "-", "14.93", "15.75", "30.92", "21.18", 
"26.85", "28.19", "28.5", "32.83", "33.22"), Oppo = c(15.89, 
18.11, 24.59, 26.7, 30.92, 26.09, 29.45, 25.66, 28.17, 28.51, 
30.56), Vivo = c("14", "14.24", "-", "-", "25.84", "24.32", "-", 
"-", "-", "-", "-"), Others = c(156.65, 159.19, 185.5, 195.06, 
125.88, 131.87, 159.55, 162.91, 153.78, 146.1, 153.96), row = 1:11), row.names = c(NA, 
-11L), class = c("tbl_df", "tbl", "data.frame"))

1 个答案:

答案 0 :(得分:1)

我不确定这是否正是您想要的,但是它应该给您一些帮助。 (顺便说一下,df是在原始帖子中定义的。)

library(tidyverse)

sCompanies <- df %>% colnames %>% setdiff(., c("X__1", "row"))
sQuarters <- df$X__1

df %>% 
  gather(., key = "variable", value = "value", -X__1) %>% 
  filter(variable != "row") %>% 
  mutate(value = ifelse(value == "-", NA, as.numeric(value))) %>%
  ggplot(., aes(x = factor(X__1, levels = sQuarters), 
                y = value, 
                fill = factor(variable, levels = sCompanies))) + 
    geom_bar(stat = "identity", position = "stack") + 
    scale_fill_discrete(name = "") + 
    scale_x_discrete(name = "")

我已将-替换为NA,并忽略了row数据。您可以使用颜色,顺序,标签来获得所需的输出。