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

时间:2015-03-18 22:03:02

标签: r ggplot2

我有以下数据框架结构

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工作吗?

2 个答案:

答案 0 :(得分:8)

呃,这就是为什么你应该总是确保你有有效的列名。首先,这是一个比较容易重现的数据集版本

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")

答案 1 :(得分:0)

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

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()

enter image description here