Using plotmath in ggplot2 with percent sign (%)

北慕城南 提交于 2020-01-10 01:47:35

问题


I would like to use Greek characters, Latin characters and the percent sign in the facet labels of a ggplot2 bar chart. Greek characters can be done with 'facet_grid(.~variable, labeller=label_parsed)':

    a<-c("Delta~V","VarcoV","Delta~V","VarcoV")
    b<-c(1,2,3,4)
    d<-c("one","one","two","two")
    mydata<-data.frame(cbind(b,a,d))
    ggplot(mydata,aes(x=d,y=b))+facet_grid(.~a, labeller=label_parsed)+geom_bar(stat="identity")

Now I also want to add a facet label that includes % and a Latin character:

    a<-c("Delta~V","VarcoV","%V","Delta~V","VarcoV","%V")
    b<-c(1,2,3,4,5,6)
    d<-c("one","one","one","two","two","two")
    mydata<-data.frame(cbind(b,a,d))
    ggplot(mydata,aes(x=d,y=b))+facet_grid(.~a, labeller= label_parsed)+geom_bar(stat="identity")

This produces the following error:

    Error in parse(text = x) : <text>:1:1: unexpected input
    1: %V
       ^

Any ideas how to include the percent sign?


回答1:


Latin characters do not need any special treatment and you can see this in the first element of a. Try this:

a<-c("Delta~V","VarcoV","'%'*V","Delta~V","VarcoV","'%'*V")

The "%" sign is special so you need to quote it. You could have just done '%V' but I threw in the "*" (asterisk) to show how to separate plotmath tokens with no displayed space. (You already appear to know how to separate tokens with the spacing-separator, "~".)

The key lesson is to mix type of quotes. The first quote type will signal which type is used to terminate the character token/string. You can also use the escape character: "\". This also succeeds:

a<-c("Delta~V","VarcoV","\"%\"*V","Delta~V","VarcoV","\"%\"*V")


来源:https://stackoverflow.com/questions/16994646/using-plotmath-in-ggplot2-with-percent-sign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!