R中堆积的条形图

时间:2016-01-13 09:14:43

标签: r bar-chart stacked

我想用R做一个堆积的条形图。 我尝试了mtcars示例,它似乎工作正常。 但是,当我用这个表累了代码时,它不起作用,我不知道它有什么问题。

data <- read.table(text = "   Solar Geothermal Coal.Gasification Hydrogen
1   9.078     14.265            18.156   22.304
                   2  10.324     24.640            29.827   35.273
                   3  14.265     29.827            38.905   45.338
                   4  16.859     40.202            50.576   57.010
                   5  20.749     53.170            66.138   75.166
                   6  38.905     73.919           103.746  115.367
                   7  97.262    175.072           262.015  272.496
                   8  80.403    173.775           390.457  319.182
                   9  88.184    184.150           399.535  398.238
                   10 89.481    172.478           383.973  404.722
                   11 90.778    158.213           421.581  391.754
                   12 92.075    165.994           413.800  430.659
                   13 82.946    142.651           416.394  429.413
                   14 76.462    129.683           355.443  438.491
                   15 76.462    130.980           372.302  377.540
                   16 69.978    124.592           377.489  396.992
                   17 75.166    128.482           289.401  395.695
                   18 76.462    128.482           295.885  298.433
                   19 71.275    121.892           264.761  307.511
                   20 76.462    123.189           250.496  280.171
                   21 77.759    116.649           254.386  260.719
                   22 77.759    119.242           238.824  268.444
                   23 79.056    116.649           221.966  262.000
                   24 75.166    114.055           206.404  248.991
                   25 81.650    114.055           189.545  228.242
                   26 90.824    123.133           308.808  210.086", header = TRUE)

library(reshape2)

data2 <- melt(data)
row <- rep(1:4,length=nrow(data2))
df <- cbind(data2, row)

library(ggplot2)

ggplot(df, aes(x=variable, y=value, fill=row)) + 
    geom_bar(stat="identity") +
    xlab("\nSource") +
    ylab("Spending\n") +
    guides(fill=FALSE) +
    theme_bw()

谢谢

1 个答案:

答案 0 :(得分:1)

ggplot2在绘图时使用数据框的顺序,因此不同的行不在一起。对数据帧进行排序就足以获得预期的结果

library(dplyr)
ggplot(arrange(df, row), aes(x=variable, y=value, fill=row)) + 
  geom_bar(stat="identity") +
  xlab("\nSource") +
  ylab("Spending\n") +
  guides(fill=FALSE) +
  theme_bw()