在ggplot中堆积的条形图

时间:2017-08-02 02:03:12

标签: r ggplot2 bar-chart stacked

我有以下数据框

    State Total_EV_1 Total_EV_2 Total_EV_3 total
    <fctr>      <int>      <int>      <int> <dbl>
1     CA        982      13166       1670 15818
2     TX        199       2169        267  2635
3     FL        329       1721        233  2283
4     WA        239       1647        161  2047
5     GA        199       1462        246  1907
6     NY         87       1475        178  1740 

我想为每个状态(在x轴上)绘制条形图,在Y轴上绘制总计,然后根据total_EV1,total_EV2,Total_EV3的数量为每个条形图着色。 total = Total_EV1 + Total_EV2 + Total_EV3

我该怎么做呢。我现在可以绘制的是状态与总数的条形图。

图片附在下面的链接

State vs total charger points

1 个答案:

答案 0 :(得分:0)

看看这是否适合你:

df <- data.frame(
                 State      = c("CA", "TX", "FL", "WA", "GA", "NY"),
                 Total_EV_1 = c(982, 199, 329, 239, 199, 87),
                 Total_EV_2 = c(13166, 2169, 1721, 1647, 1462, 1475),
                 Total_EV_3 = c(1670, 267, 233, 161, 246, 178),
                 total      = c(15818, 2635, 2283, 2047, 1907, 1740)
                 )
      
library(tidyverse)      

df1 <- df %>% select(-total) %>%
      gather(Type, Value, -State) %>%
      mutate(State = factor(State, 
                     levels = c("CA", "TX", "FL", "WA", "GA", "NY")))
                     
ggplot(data = df1, aes(x = State, y = Value))+ 
      geom_bar(aes(fill = Type), stat = "identity")