ggplot:没有 aes_string 的变量字符串的美学
ggplot: aesthetics from variable string without aes_string
我有一个包含 data.frame
列名称的变量 v
。
我现在想根据它的索引绘制它。
通常情况下,根据其索引绘制列很容易:
df <- data.frame(a = c(.4, .5, .2))
ggplot(df, aes(seq_along(a), a)) + geom_point()
但在我的情况下,我不知道要做什么咒语:
plot_vs <- function(df, count = 2) {
vs <- paste0('V', seq_len(count)) # 'V1', 'V2', ...
for (v in vs) {
# this won’t work because “v” is a string
print(ggplot(df, aes(seq_along(v), v)) + geom_point())
# maybe this? but it also doesn’t work (“object ‘v.s’ not found”)
v.s <- as.symbol(v)
print(ggplot(df, aes(seq_along(v.s), v.s)) + geom_point())
# this doesn’t work because i use seq_along, and seq_along('V1') is 1:
print(ggplot(df, aes_string(seq_along(v), v)) + geom_point())
}
}
plot_vs(data.frame(V1 = 4:6, V2 = 7:9, V3 = 10:12))
library(ggplot2)
df <- data.frame(a = c(.4, .5, .2))
v <- "a"
df$num<-seq(nrow(df))
ggplot(df, aes_string("num", v)) + geom_point()
您的问题标题明确指出您想在没有 aes_string
的情况下执行此操作。以下是使用 aes_string
的方法:使用 paste
。
plot_vs <- function(df, count = 2) {
vs <- paste0('V', seq_len(count)) # 'V1', 'V2', ...
for (v in vs) {
print(ggplot(df, aes_string(paste("seq_along(", v, ")"), v)) + geom_point())
}
}
plot_vs(data.frame(V1 = 4:6, V2 =7:9, V3 = 10:12))
@shadow的评论给出了求解的提示,即aes_q
:
plot_vs <- function(df, count = 2) {
vs <- paste0('V', seq_len(count)) # 'V1', 'V2', ...
for (v in vs) {
v = as.name(v)
print(ggplot(df, aes_q(substitute(seq_along(v)), v)) + geom_point())
}
}
plot_vs(data.frame(V1 = 4:6, V2 = 7:9, V3 = 10:12))
我有一个包含 data.frame
列名称的变量 v
。
我现在想根据它的索引绘制它。
通常情况下,根据其索引绘制列很容易:
df <- data.frame(a = c(.4, .5, .2))
ggplot(df, aes(seq_along(a), a)) + geom_point()
但在我的情况下,我不知道要做什么咒语:
plot_vs <- function(df, count = 2) {
vs <- paste0('V', seq_len(count)) # 'V1', 'V2', ...
for (v in vs) {
# this won’t work because “v” is a string
print(ggplot(df, aes(seq_along(v), v)) + geom_point())
# maybe this? but it also doesn’t work (“object ‘v.s’ not found”)
v.s <- as.symbol(v)
print(ggplot(df, aes(seq_along(v.s), v.s)) + geom_point())
# this doesn’t work because i use seq_along, and seq_along('V1') is 1:
print(ggplot(df, aes_string(seq_along(v), v)) + geom_point())
}
}
plot_vs(data.frame(V1 = 4:6, V2 = 7:9, V3 = 10:12))
library(ggplot2)
df <- data.frame(a = c(.4, .5, .2))
v <- "a"
df$num<-seq(nrow(df))
ggplot(df, aes_string("num", v)) + geom_point()
您的问题标题明确指出您想在没有 aes_string
的情况下执行此操作。以下是使用 aes_string
的方法:使用 paste
。
plot_vs <- function(df, count = 2) {
vs <- paste0('V', seq_len(count)) # 'V1', 'V2', ...
for (v in vs) {
print(ggplot(df, aes_string(paste("seq_along(", v, ")"), v)) + geom_point())
}
}
plot_vs(data.frame(V1 = 4:6, V2 =7:9, V3 = 10:12))
@shadow的评论给出了求解的提示,即aes_q
:
plot_vs <- function(df, count = 2) {
vs <- paste0('V', seq_len(count)) # 'V1', 'V2', ...
for (v in vs) {
v = as.name(v)
print(ggplot(df, aes_q(substitute(seq_along(v)), v)) + geom_point())
}
}
plot_vs(data.frame(V1 = 4:6, V2 = 7:9, V3 = 10:12))