简体   繁体   English

在 ggplot2 中合并图例的标题中使用上标

[英]Use a superscript in the title of a merged legend in ggplot2

I am making a scatter plot with ggplot, changing both color and shape according to a variable, as in this image generated by the code below.我正在使用 ggplot 制作散点图,根据变量更改颜色和形状,如下面的代码生成的图像所示。

a<-c(2,5,2,6,1,2,3,6)
b<-c(5,2,6,7,8,3,1,9)
c<-c(rep("n",4),rep("m",4))
data<-data.frame(a,b,c)

ggplot(data,aes(a,b,shape=c,color=c))+
  geom_point()

情节不变

Both color and shape can be seen in the same legend, just as intended.正如预期的那样,可以在同一个图例中看到颜色和形状。 If a make a simple change in the title, I have to do it for both shape color and shape, and it works fine.如果对标题进行简单的更改,我必须对形状颜色和形状都进行更改,并且效果很好。

ggplot(data,aes(a,b,shape=c,color=c))+
  geom_point()+
  labs(color="dif",shape="dif")

简单的改变

The problem comes when I write superscripts using expression() .当我使用expression()编写上标时,问题就出现了。 If I use expression with simple words it works fine too, but when superscripts are added, then the legends for shape and color don't merge again.如果我使用带有简单单词的表达式它也可以正常工作,但是当添加上标时,形状和颜色的图例不会再次合并。

ggplot(data,aes(a,b,shape=c,color=c))+
  geom_point()+
  labs(color=expression((ng~g^{-1})),shape=expression((ng~g^{-1})))

错误的传说

Any solution for this problem?这个问题有什么解决方案吗?

You can avoid this stange behavior if you store the expression in an object:如果将表达式存储在对象中,则可以避免这种奇怪的行为:

title_exp <- expression((ng~g^{-1}))

ggplot(df, aes(a, b, shape = c, color = c)) +
  geom_point() + 
  labs(color = title_exp, shape = title_exp)

固定标题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM