我想做什么
我有一个图,其中 x = 类别变量(国家/地区),y = 数字变量(响应)。我想循环代码,以便所有剩余的数字变量(请参见下面的示例 df)也使用相同的 x = 分类变量进行绘制,而不必每次都重新创建相同的代码段。
我尝试做/计划的事情
我有我想要循环的情节的代码。我已将其设置为函数,因为我想使用相同的代码,但每次使用不同的 y 值。
par(mfrow(c = 2,3))
fun_1 <- function (x)
x <- small_df %>%
ggplot(aes(Country, Response, color = Country))+
geom_point() +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
然后我认为下一步是创建一个 for 循环,但我在 R 方面的能力已经不够了。我知道 for 循环中需要包含什么,但我无法弄清楚如何真正开始自己的编码过程。
我的数据框有 7 行和 5 个变量。
我想象循环的结构如下:
for(i in 1:7) { ## loop for each row in df
Where X = Country is constant for each loop
Loop the function for all the remaining Y (BNP_USD, Currency, BirthRate)
Print out a plot for each X and Y combination
}
打印图
简单数据示例
假设数据框如下:
Country <- c("BDG", "CHN", "MMR", "IDN", "IND", "LKA", "KHM")
Response <- c(30, 15, 25, 10, 11, 21, 16)
BNP_USD <- c(10000,20000,30000,40000,50000,60000,70000)
Currency <- c(0.1, 3.2, 6.02, 8.0, 7.5, 0.06, 8.8)
BirthRate <- c(4, 2, 3, 4, 2, 2, 2)
df <- data.frame(Country, Response, BNP_USD, Currency, BirthRate)
预期结果将是所有数值变量的图,所有数值变量都具有 x = 国家/地区。
最佳答案
这是一个tidyverse
选项,它使用一些 reshape 和facet_wrap
:
library(tidyverse)
df %>%
gather(variable, value, -Country) %>%
ggplot(aes(Country, value, color = variable))+
geom_point() +
theme(axis.text.x = element_text(angle = 90, hjust = 1))+
facet_wrap(~variable, scales = "free")
如果您愿意,可以删除图例。
不确定这是否是您理想的输出/绘图,或者您是否更喜欢单独显示每个输出/绘图,但这是执行一些数据探索的一种非常简单且直接的方法。
关于r - 如何将绘图组合循环到数据框中的剩余变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57091830/