簡體   English   中英

如何在 R 中的一個圖中創建 2 個圖形?

[英]How do I create 2 graphs in one plot in R?

到目前為止,我已經分別創建了兩個圖

1.

library(tidyverse)

# going to to create my X axis which will be time 
x<- c(1950:1991)

# Create my Y values, which is the mean for every year that the summary command will show

summary(Data_Set_For_Earsten_Political_Block)

y <- c(61.00,61.44,62.23,63.01,63.75,64.47,65.15,65.79,66.40,66.96,67.50,67.96,68.40,68.77,69.11,69.40,69.66,69.90,70.11,70.29,70.49,70.65,70.81,70.93,71.05,71.17,71.27,71.37,71.47,71.56,71.67,71.79,71.93,72.08,72.23,72.39,72.50,72.58,72.65,72.67,72.67,72.66)

# Make Plot:

plot(x,y, xlab = "Year", ylab = "Average Life Expectancy For Females", main = "Life Expectancy For Females in The Eastern Political Block", type = "o", col="red", pch =20, lwd=2)

2.

z <-c(70.13,70.33,70.73,71.10,71.44,71.78,72.10,72.39,72.66,72.91,73.17,73.38,73.60,73.78,73.96,74.14,74.32,74.50,74.68,74.87,75.08,75.28,75.52,75.78,76.03,76.34,76.62,76.90,77.14,77.41,77.62,77.83,78.03,78.21,78.40,78.58,78.73,78.93,79.08,79.24,79.41,79.54)

# Creating plot: 

plot(x,z, xlab = "Year", zlab = "Average Life Expectancy For Females", main = "Life Expectancy For Females in The Western Political Block", type = "o", col="blue", pch =20, lwd=2)

我如何將這兩個圖組合成一個圖,以便我可以直觀地比較它們?

正如@r2evans 所提到的,最簡單的方法是設置par(mfrow = c(2,1))

par(mfrow = c(2,1))
plot(x,y, xlab = "Year", ylab = "Average Life Expectancy For Females", main = "Life Expectancy For Females in The Eastern Political Block", type = "o", col="red", pch =20, lwd=2)
plot(x,z, xlab = "Year", zlab = "Average Life Expectancy For Females", main = "Life Expectancy For Females in The Western Political Block", type = "o", col="blue", pch =20, lwd=2)

在此處輸入圖片說明

或者,您可以通過使用這些小區聯合收割機值轉換成一個數據幀tidyverse和使用繪制出來ggplot2

df = data.frame(cbind(x,y,z))
df %>% pivot_longer(.,-x, names_to = "Variable", values_to = "Value") %>%
  ggplot(., aes(x = x, y = Value, color = Variable)) +
  geom_point() +
  geom_line() +
  xlab("Year") +
  ylab("Average Life Expectancy For Females") + 
  scale_color_discrete(breaks = c("y","z"), labels = c("Eastern", "Western"))

在此處輸入圖片說明

如果你真的更喜歡分開繪圖,你可以像這樣添加facet_wrap的參數:

labels = c(y = "Eastern", z = "Western")
df %>% pivot_longer(.,-x, names_to = "Variable", values_to = "Value") %>%
    ggplot(., aes(x = x, y = Value, color = Variable)) +
    geom_point() +
    geom_line() +
    xlab("Year") +
    ylab("Average Life Expectancy For Females") + 
    scale_color_discrete(breaks = c("y","z"), labels = c("Eastern", "Western")) +
  facet_wrap(.~Variable, labeller = labeller(Variable = labels))

在此處輸入圖片說明

它回答你的問題嗎?

如果您想要更多使用ggplot2繪圖的ggplot2 ,您可以查看ggplot2 for R

暫無
暫無

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

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