簡體   English   中英

如何在一個 plot 中合並估計和投影圖?

[英]How to merge estimation and projection graphs in one plot?

我訪問了這張自 2000 年起每兩年估計數據點的糖尿病病例數估計和未來預測數字的圖表。該圖表實際上是不正確的,因為線上的點與左側的比例不一致。 我正在嘗試在 ggplot2 或 ggplotly 中重新繪制它。 在重新繪制時,我打算在單個 plot 中制作兩個折線圖 - 一個用於過去幾年的估計,另一個用於未來 20-25 年的未來預測以及做出預測的年份。 任何幫助都是非常可觀的。 在此處輸入圖像描述

這是用於 plot 圖表的數據 - 帶有年份的估計數字用藍色表示,而未來年份的預計數字用紅線表示。 由於幾年內有多個預計數字,因此我打算將最高數字保留在折線圖上。

估計年份 估計(百萬) 預測(百萬) 預測年份
2000 151 333 2025
2003年 194 380 2025
2006年 246 438 2030
2009 285 552 2030
2011 366 578 2030
2013 382 592 2035
2015 415 642 2040
2017 425 629 2045
2019 463 700 2045

您的問題更多是關於數據爭吵,而不是使用 ggplot 進行實際繪圖。 一旦你有正確形狀的數據,繪圖命令只是幾行。

  1. 為估計(藍色)點准備數據。 將列type設置為“估計”。
  2. 准備投影(紅色)點的數據。 將列type設置為“投影”。
  3. 使用bind_rows組合兩個表。
  4. 在 ggplot 的美學中使用color=type

這是您如何 go 從數據中重新創建 plot 的開始。 我沒有花任何精力來重建氣球,將主題設置為更優雅的東西和那些東西。

library(ggplot2)

txt <- "2000    151 333 2025
2003    194 380 2025
2006    246 438 2030
2009    285 552 2030
2011    366 578 2030
2013    382 592 2035
2015    415 642 2040
2017    425 629 2045
2019    463 700 2045"

df <- read.table(text = txt)

# Putting years and values in the same columns
# Probably some tidyverse function can do this more elegantly
df <- rbind(cbind(unname(df[1:2]), type = "Estimates"),
            cbind(unname(df[4:3]), type = "Projection"))
colnames(df) <- c("year", "value", "type")

# We're reordering on value, because the red line does not touch year-duplicates
df <- df[order(df$value, decreasing = TRUE),]

ggplot(df, aes(year, value, colour = type)) +
  # Formula notation to filter out data for the line
  geom_line(data = ~ subset(., !duplicated(year))) +
  geom_point() +
  scale_colour_manual(
    values = c("Estimates" = "dodgerblue",
               "Projection" = "tomato")
  ) +
  scale_y_continuous(limits = c(0, NA),
                     name = "Millions")

代表 package (v0.3.0) 於 2021 年 1 月 6 日創建

暫無
暫無

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

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