有没有一种方法可以在不输入列名的情况下使用 ggplot aes 标注,而只需输入列#?

is there a way to use the ggplot aes callout without inputing the column name but by just inputting the column #?

EXAMPLE DATASET:
mtcars 
               mpg cyl disp  hp drat   wt ... 
Mazda RX4     21.0   6  160 110 3.90 2.62 ... 
Mazda RX4 Wag 21.0   6  160 110 3.90 2.88 ... 
Datsun 710    22.8   4  108  93 3.85 2.32 ... 
               ............

推荐的ggplot方式:

ggplot(mtcars,aes(x=mpg)) + geom_histogram

他们是我想要的方式:

ggplot(mtcars,aes(x=[,1]) +geom_histogram

ggplot(mtcars,aes(x=[[1]]))+geom_histogram

为什么 ggplot 不能让我按列调出我的变量?我需要按列号而不是名称来调用它。为什么ggplot在这里如此严格?有什么解决办法吗?

您面临的问题是 ggplot aes 参数在您传递给它的 data.frame 中计算。列名是一个字符串,不能以相同的方式正确计算。

幸好有解决办法:使用aes_string选项,如下:

library(ggplot2)

my_data <- mtcars

names(my_data)

ggplot(my_data, aes_string(x=names(my_data)[1]))+
  geom_histogram()

这是可行的,因为 names(my_data)[1] returns 是一个字符串,并且对于 aes_string 选项来说是完全可以接受的。