如果我了解您的要求,则应执行以下操作。首先,制作一些可复制的数据,大致与您描述的内容相同:
library(magrittr)
library(tidyverse)
data <- tibble(y = rnorm(10),category = factor(sample(1:9,10,replace = TRUE))) %>%
inset(paste0("x",1:11),value = rnorm(110)) %>%
pivot_longer(-c(y,category),names_to = "x_name",values_to = "x")
数据如下:
# A tibble: 6 x 4
y category x_name x
<dbl> <fct> <chr> <dbl>
1 1.84 6 x1 1.06
2 1.84 6 x2 0.744
3 1.84 6 x3 -1.19
4 1.84 6 x4 1.88
5 1.84 6 x5 2.16
6 1.84 6 x6 -1.58
然后您可以在此处使用facet_wrap
为每个x_name
创建一个带有面板的网格。我添加了geom_smooth
是很不错的选择:
ggplot(data,aes(x = x,y = y)) +
geom_point(aes(colour = category)) +
facet_wrap(~x_name) +
geom_smooth(method = "lm")
,
我也建议您提供一个可复制的示例。
ggplot代替了“ par(mfrow)”,使用了facetting的概念。在这里看看:ggplot facetting
library(tidyr)
library(dplyr)
library(ggplot2)
# assuming the names of your dataframe hd are like this:
names(hd) = c('y','cat','x1','x2','x3','x4','x5','x6','x7','x8','x9')
# then,the following code could solve your problem:
hd %>%
pivot_longer(x1:x9,names_to=var_x,values_to=val_x) %>%
ggplot(hd,aes(x=y,y=val_x,colour=cat)) +
geom_point() +
facet_wrap(~var_x,ncol=3)
本文链接:https://www.f2er.com/3118768.html