将 ggplot2 与名称中包含空格的列一起使用

Using ggplot2 with columns that have spaces in their names

我有以下数据帧结构

df <- as.data.frame(A)
colnames(df)<- c("Sum of MAE", "Company")
df <- na.omit(df)
df2 <- df[order(df[,1]),]
df2 <- head(df2, n=10)
ggplot(df2, aes_string("Sum of MAE", "Company", group=1) + geom_line())
print(df2)

这是数据的结构

 Sum of MAE Company
606   0.030156758080105    COCO
182  0.0600065426668421    APWC
836  0.0602272459239397     EDS
1043 0.0704327240953608    FREE
2722               0.09   VLYWW
1334 0.0900000000000001    IKAN
2420  0.104746328560384     SPU
860   0.106063964745531    ELON
2838  0.108373386847075    WTSL
1721  0.110086738825851    MTSL

ggplot 似乎不起作用。在出现一连串错误之后,我得到的当前错误是

Error in parse(text = x) : <text>:1:5: unexpected symbol
1: Sum of

谁能帮我让 ggplot 2 工作。

这是一个很好的理由,您应该始终确保您拥有有效的列名。首先,这是一个更容易重现的数据集版本

df2 <- data.frame(`Sum of MAE` = c(0.030156758080105, 0.0600065426668421, 
   0.0602272459239397, 0.0704327240953608, 0.09, 0.0900000000000001, 
   0.104746328560384, 0.106063964745531, 0.108373386847075, 0.110086738825851
   ), Company = c("COCO", "APWC", "EDS", "FREE", "VLYWW", "IKAN", "SPU", "ELON", 
   "WTSL", "MTSL"), check.names=F)

ggplot(df2, aes_string("Sum of MAE", "Company", group=1) + geom_line())
# Error in parse(text = x) : <text>:1:5: unexpected symbol
# 1: Sum of
#         ^

问题是 aes_string() 使用 parse() 将您的文本表达式转换为可以在 data.frame 中解析的正确 R 符号。当您解析不是有效 R 语法的“MAE 之和”时——也就是说,它不会解析为单个漂亮的符号名称。如果你使用这样的“坏”名字,你可以用反引号将它们转义,将表达式(空格和所有)视为一个符号。所以你可以做

ggplot(df2, aes_string("`Sum of MAE`", "Company", group=1)) + geom_line()
# or
ggplot(df2, aes(`Sum of MAE`, Company, group=1)) + geom_line()

但实际上最好坚持为您的 data.frame 使用有效的列名,而不是绕过 colnames() 的检查。

如果您要更改列名以获得“更好”的轴标签,您可能应该改用 xlab() 来做。例如

df3 <- data.frame(df2)
names(df3)
# [1] "Sum.of.MAE" "Company" 
ggplot(df3, aes(Sum.of.MAE, Company, group=1)) + 
    geom_line() + 
    xlab("Sum of MAE values")

不知道你想画什么,这是一个开始(其他人可能会更好地理解)。

df <- read.table(textConnection(" 
                                606   0.030156758080105    COCO
                                182  0.0600065426668421    APWC
                                836  0.0602272459239397     EDS
                                1043 0.0704327240953608    FREE
                                2722               0.09   VLYWW
                                1334 0.0900000000000001    IKAN
                                2420  0.104746328560384     SPU
                                860   0.106063964745531    ELON
                                2838  0.108373386847075    WTSL
                                1721  0.110086738825851    MTSL"))
colnames(df) <- c("sum", "MAE", "Company")
ggplot(df, aes(x=Company, y=MAE, group = 1)) +
  geom_line()