R中具有多个变量的条形图

时间:2019-04-16 21:27:08

标签: r

我正在研究R中的航班数据集。我想将以下数据绘制在一个条形图中。

flight_month early_arrival delayed_arrival ealry_departure
1        April     -15.58233        42.73958       -5.058515
2       August     -17.16566        39.51294       -4.676996
3     December     -14.02251        39.72725       -4.533339
4     February     -15.85862        33.68921       -4.912044
5      January     -15.09903        34.47749       -4.906270
6         July     -16.79175        53.95152       -4.562090
  delay_departure
1        44.05532
2        37.22452
3        37.06027
4        35.17606
5        35.24179
6        48.54883

与此类似,但显示了所有变量。

serialize

average<-read.csv('Average.csv')
ggplot(average,aes(x=flight_month,y=delayed_arrival))+
  geom_bar(stat="identity")

这是我尝试过的方法,但是通过这种方式,我只能在y轴上看到delay_arrival,我想在y轴上看到所有四个变量。以及x轴上的月份。

1 个答案:

答案 0 :(得分:1)

void arrange(int* a, int* b) {
    std::priority_queue<int*, std::vector<int>, compr> q;
    q.push(a);
    q.push(b);
}

struct compr {
    bool operator()(const int& lhs, const int& rhs) const {
        if (lhs%2==0 && rhs%2==0) {
            return lhs>rhs;
        }
        return false;
    }
};

这是一个示例图:

library(ggplot2)
library(dplyr)
library(tibble)
library(tidyr)

或者您可以重塑数据:

df %>% ggplot(aes(flight_month, group = 1)) + 
  geom_bar(aes(y = early_arrival), stat = "identity", fill = "blue")+
  geom_bar(aes(y = delayed_arrival), stat = "identity", fill = "red") 

以下是新数据的示例:

df %>% tidyr::gather("metrics", "value", -flight_month) %>% 
  ggplot(aes(flight_month, value, group= metrics, fill = metrics)) +
           geom_bar(stat = "identity", width=.5, position = "dodge")

数据:

# A tibble: 24 x 3
   flight_month metrics         value
   <chr>        <chr>           <dbl>
 1 April        early_arrival   -15.6
 2 August       early_arrival   -17.2
 3 December     early_arrival   -14.0
 4 February     early_arrival   -15.9
 5 January      early_arrival   -15.1
 6 July         early_arrival   -16.8
 7 April        delayed_arrival  42.7
 8 August       delayed_arrival  39.5
 9 December     delayed_arrival  39.7
10 February     delayed_arrival  33.7
# ... with 14 more rows