问题:使用因子的索引绘制变量
Question: Use a factor's index to plot variables
我是 R 的新手,所以如果这真的很简单,我很抱歉。
我查看了一堆备忘单,但看不到任何明显的东西。
我有一组简单的数据,其中包含日期、温度和 4 个不同的因素(基于树的开花 // 1 = "", 2 = "bloom", 3 = "full", 4 = "scatter")
我想做的,但不知道怎么做,是分别绘制每个因素的日期和温度的散点图。
一种方法是将 ggplot2
与 facet_wrap
结合使用。首先,一定要设置 Bloom
因子的级别名称,这样绘图才会有用。
然后,我们使用 ggplot
绘制数据,并使用 group =
Bloom
因子。然后我们添加 facet_wrap
,公式是 .
(所有其他)应该按 Bloom
分组。
library(ggplot2)
levels(TreeData$Bloom) <- c("None","Bloom","Full","Scatter")
ggplot(TreeData, aes(x=Date,y=Temp,group = Bloom, color = Bloom)) +
geom_point(show.legend = FALSE) +
facet_wrap(. ~ Bloom)
根据你的评论,如果你想要单独的图表,你可以使用带有 TreeData[TreeData$Bloom == "Full",]
的基本 R 子集。请注意,"Full" 是我们之前设置的因子水平。
ggplot(TreeData[TreeData$Bloom == "Full",], aes(x=Date,y=Temp)) +
geom_point() + labs(title="Full Bloom")
数据
set.seed(1)
TreeData <- data.frame(Date = rep(seq.Date(from=as.Date("2019-04-01"), to = as.Date("2019-08-01"), by = "week"),each = 10) , Temp = round(runif(22,38,n=180)), Bloom = as.factor(sample(1:4,180,replace = TRUE)))
我是 R 的新手,所以如果这真的很简单,我很抱歉。 我查看了一堆备忘单,但看不到任何明显的东西。
我有一组简单的数据,其中包含日期、温度和 4 个不同的因素(基于树的开花 // 1 = "", 2 = "bloom", 3 = "full", 4 = "scatter")
我想做的,但不知道怎么做,是分别绘制每个因素的日期和温度的散点图。
一种方法是将 ggplot2
与 facet_wrap
结合使用。首先,一定要设置 Bloom
因子的级别名称,这样绘图才会有用。
然后,我们使用 ggplot
绘制数据,并使用 group =
Bloom
因子。然后我们添加 facet_wrap
,公式是 .
(所有其他)应该按 Bloom
分组。
library(ggplot2)
levels(TreeData$Bloom) <- c("None","Bloom","Full","Scatter")
ggplot(TreeData, aes(x=Date,y=Temp,group = Bloom, color = Bloom)) +
geom_point(show.legend = FALSE) +
facet_wrap(. ~ Bloom)
根据你的评论,如果你想要单独的图表,你可以使用带有 TreeData[TreeData$Bloom == "Full",]
的基本 R 子集。请注意,"Full" 是我们之前设置的因子水平。
ggplot(TreeData[TreeData$Bloom == "Full",], aes(x=Date,y=Temp)) +
geom_point() + labs(title="Full Bloom")
数据
set.seed(1)
TreeData <- data.frame(Date = rep(seq.Date(from=as.Date("2019-04-01"), to = as.Date("2019-08-01"), by = "week"),each = 10) , Temp = round(runif(22,38,n=180)), Bloom = as.factor(sample(1:4,180,replace = TRUE)))