簡體   English   中英

如何繪制線以將這些點加入ggplot?

[英]How do I draw lines to join these points in ggplot?

我正在嘗試使用以下代碼繪制圖形。

ggplot(test2, aes(x = Month, y = Spend, color = YEAR)) +
    geom_point()

輸出如下所示。 但是,我想加入每年的積分/抽獎線。 我嘗試了geom_line和geom_abline,但它們無法正常工作。 我有什么辦法可以做到這一點?

在此處輸入圖片說明

資料集:

structure(list(Month = c("01", "01", "02", "02", "03", "03", 
"04", "04", "05", "05", "06", "06", "07", "07", "08", "08", "09", 
"09", "10", "10", "11", "11", "12", "12"), YEAR = structure(c(1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("2016", "2017"), class = "factor"), 
    Spend = c(66142.27, 75735, 61247.19, 65126.4, 65947.08, 73293.63, 
    63489.61, 72500.34, 64634.54, 69689.61, 60988.69, 67231.09, 
    64966.94, 72014.3, 66683.24, 70857.17, 65637.03, 68606.12, 
    69224.13, 71083.37, 65561.6, 70094.81, 66152.87, 67784.81
    )), row.names = c(NA, -24L), class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"), vars = "Month", drop = TRUE, indices = list(
    0:1, 2:3, 4:5, 6:7, 8:9, 10:11, 12:13, 14:15, 16:17, 18:19, 
    20:21, 22:23), group_sizes = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L), biggest_group_size = 2L, labels = structure(list(
    Month = c("01", "02", "03", "04", "05", "06", "07", "08", 
    "09", "10", "11", "12")), row.names = c(NA, -12L), class = "data.frame", vars = "Month", drop = TRUE))

您需要將YEAR映射到geom_linegroup美學,因為Month是字符類型。

您必須已閱讀:

geom_path:每個組僅包含一個觀測值。 您是否需要調整小組審美?

ggplot(test2, aes(x = Month, y = Spend, color = YEAR)) +
  geom_line(aes(group = YEAR)) +
  geom_point()

在此處輸入圖片說明

解決方法如下:

ggplot(test2, aes(x = Month, y = Spend, color = YEAR)) +
  geom_point() + 
  geom_path(aes(group = YEAR))

geom_path是您想要的,享受

暫無
暫無

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

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