簡體   English   中英

如何在R中用折線圖覆蓋條形圖?

[英]How to overlay a bar chart with a line chart in R?

我希望以數周為基礎,將數據擱置多年。 我正在尋找最近的一年(2020 年)是酒吧聊天,而前幾年(2019 年和 2018 年)是線圖。

我當前的代碼產生下面的視覺效果

data %>%
  ggplot(aes(week, result, fill = year)) +
  geom_col()

圖表

如果我想將所有年份制作成條形圖,我知道我可以在 geom_col 中使用“dodge”。 但是,我正在嘗試將數據拆分為不同的幾何體

當我使用子集函數(下面的代碼)時,我的圖表發生了一些奇怪的事情,我無法弄清楚發生了什么

data %>%
  ggplot(aes(week, result, fill = year)) +
  geom_col(data = subset(data, year == 2020)) +
  geom_line(data = subset(data, year != 2020))

圖二

以下是我正在使用的數據示例。 關於我做錯了什么的任何想法?

structure(list(year = c("2018", "2018", "2019", "2019", "2020", 
"2020"), week = c(1L, 2L, 1L, 2L, 1L, 2L), result = c(6.88475831020016, 
7.62267452779933, 3.67553313593328, 6.18354398162893, 2.38101968527051, 
5.9596355812872)), .Names = c("year", "week", "result"), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

我不確定您的錯誤在哪里,但是我的虛擬示例模仿了您的示例,我只是在aes中添加color以使行按年份分組,其余代碼與您的類似:

ggplot(df, aes(x = week, y = Value, 
               color = as.factor(year),
               fill = as.factor(year)))+
  geom_col(data = subset(df, year == 2020)) +
  geom_line(data = subset(df, year != 2020))

在此處輸入圖片說明

數據

df <- data.frame(year = rep(2018:2020, each = 7),
                 week = rep(1:7,3),
                 Value = rnorm(21))

使用 OP 數據進行編輯

根據您的數據,您只需要根據@camille 指出的字符值而不是數字進行子集化:

ggplot(df, aes(x = week, y = result, 
                 color =year,
                 fill = year))+
    geom_col(data = subset(df, year == "2020")) +
    geom_line(data = subset(df, year != "2020"))

在此處輸入圖片說明

暫無
暫無

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

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