簡體   English   中英

R中具有多個變量的條形圖

[英]Bar plot with multiple variables in 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

與此類似,但顯示所有變量。

條形圖

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

這是我嘗試過的,但這樣我只能在 y 軸上看到 delay_arrival,我想在 y 軸上看到所有四個變量。 以及 x 軸上的月份。

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

數據:

df <- structure(list(flight_month = c("April", "August", "December", 
"February", "January", "July"), early_arrival = c(-15.58233, 
-17.16566, -14.02251, -15.85862, -15.09903, -16.79175), delayed_arrival = c(42.73958, 
39.51294, 39.72725, 33.68921, 34.47749, 53.95152), early_departure = c(-5.058515, 
-4.676996, -4.533339, -4.912044, -4.90627, -4.56209), delay_departure = c(44.05532, 
37.22452, 37.06027, 35.17606, 35.24179, 48.54883)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM