簡體   English   中英

創建分組條形圖

[英]Creating a grouped bar chart

我對 R 非常陌生,所以如果簡化了解釋,這將非常有幫助。

一段時間以來,我一直在努力在 R 中創建分組條形圖。 我想在我的 x 軸上有幾個月的時間。 我希望條形圖也按兩個變量分組。

這是我到目前為止嘗試過的代碼:

library(reshape2)
library(ggplot2)
Months2 <- c('January','February','March','April','May','June','July','August','September','October','November','December')
Qantas <- c(18775,16560,21093,16101,15948,18864,17252,16770,21082,16692,15795,21782)
Ideal <- c(16591,21570,20579,16048,14372,15269,18266,17488,16284,17794,18880,23600)

# reshaping into longdata
InboundQantaslong <- melt(InboundQantas, id=c("Month"))

# make the plot
ggplot(InboundQantaslong) +
  geom_bar(aes(x = Months2, y = value, fill = variable), 
           stat="identity", position = "dodge", width = 0.7) +
  scale_fill_manual("Number\n", values = c("red","blue"), 
                    labels = c(" Ideal", " Qantas")) +
  labs(x="\nMonth",y="Number\n") +
  theme_bw(base_size = 14)

這將返回錯誤

手動刻度中的值不足。 需要 15 個,但只提供了 2 個。

我該如何解決?

您可以更正您的代碼,例如

library(reshape2)
library(ggplot2)

InboundQantas <- cbind.data.frame(Months2,Qantas,Ideal)

# reshaping into longdata
InboundQantaslong <- melt(InboundQantas, id=c("Months2"))
InboundQantaslong$Months2 <- factor(InboundQantaslong$Months2, levels = c("January", "February", "March", "April", "May", "June", "July", "August", "September","October","November","December"))

ggplot(InboundQantaslong, aes(x = Months2, y = value, fill = variable)) +
  geom_bar(stat="identity", position = "dodge", width = 0.7) +
  scale_fill_manual("Number\n", values = c("red","blue"), 
                    labels = c(" Ideal", " Qantas")) +
  labs(x="\nMonth",y="Number\n") +
  theme_bw(base_size = 14)

或者使用tidyversemelt替換為pivot_longer類的

InboundQantas$Months2 <- factor(InboundQantas$Months2, levels = c("January", "February", "March", "April", "May", "June", "July", "August", "September","October","November","December"))

InboundQantas %>% pivot_longer(-Months2, names_to = "variable", values_to = "value") %>% 
  ggplot(aes(x = Months2, y = value, fill = variable)) +
  geom_bar(stat="identity", position = "dodge", width = 0.7) +
  scale_fill_manual("Number\n", values = c("red","blue"), 
                    labels = c(" Ideal", " Qantas")) +
  labs(x="\nMonth",y="Number\n") +
  theme_bw(base_size = 14)

在此處輸入圖像描述

暫無
暫無

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

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