通过某些表达式在ggplot中合并图例失败

时间:2018-12-10 14:01:18

标签: r ggplot2

在此世界地图中:

library(ggplot2)
library(maps)
library(ggrepel)

data <- data.frame(Location=c("A", "B", "C"), Value=c(1000,1500,2000), Lat=c(20,30,40), Lon=c(10,-10,0))
mdat <- map_data('world')
p0 <- ggplot() + 
  geom_polygon(dat=mdat, aes(long, lat, group=group), col="gray70", fill="gray80") +
  geom_point(data=data, aes(x=Lon, y=Lat, col=Value, size=Value)) +
  #geom_text(data=data, aes(x=Lon, y=Lat, label=Location), col="red")+
  theme_bw()+
  scale_color_gradient(limits=c(50,2000),breaks=c(50,500,1000,1500,2000),low='green', high='red')+
  scale_size(limits=c(0,2000),breaks=c(50,500,1000,1500,2000))+
  geom_label_repel(data=data, aes(x=Lon, y=Lat, label=Location), col="blue",
                   box.padding   = 0.35, 
                   point.padding = 0.5,
                   size=2.5,
                   segment.color = 'grey50') +
  theme(plot.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank())
p0

图例可以与以下项合并:

p0 + guides(color=guide_legend("Some Title"),
            size = guide_legend("Some Title"))

即使表达式也可以工作:

p0 + guides(color=guide_legend(expression(CH[4])),
            size = guide_legend(expression(CH[4])))

但是,使用此特定表达式,图例不再合并:

p0 + guides(color=guide_legend(expression(Fe^{2+''})),
            size = guide_legend(expression(Fe^{2+''})))  

我在哪里弄糟?

1 个答案:

答案 0 :(得分:2)

您要在bquote上使用expression。不能完全确定背后的机制或原因。

p0 + guides(color = guide_legend(bquote(Fe^{2+''})),
            size = guide_legend(bquote(Fe^{2+''})))

enter image description here