繁体   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