如何在ggplot中使用带有directlabels的表达式

时间:2014-10-20 11:49:17

标签: r ggplot2 label scatter-plot direct-labels

我一直在寻找避免散点图中labbels重叠的方法。我发现直接标签工作正常,但不允许我使用表达式作为标签,也不允许选择我想要显示的标签和不显示的标签。

以下是一个例子:

p1使用geom_text()绘制一些(我选择的)带有表达式解析的标签,允许像希腊字母和上标之类的东西,但标签可以重叠。

p2避免与directlabels()重叠,但我无法控制绘制哪些标签,也无法使用表达式解析。

我如何才能拥有这两种方法的优势?

require(ggplot2)
require(directlabels)

par <- c("Ei", "Gb", "Gf", "Gl", "w1", "w2", "w3", "w4",
     "w5", "Alpha", "Beta", "Amin", "dl", "df")
df <- data.frame(x=runif(14), y=runif(14), Parameters=par)

# labels with expressions
labels <- c("Ei" = 'E[i]', "Gb" = 'G[b]', "Gf" = 'G[f]', "Gl" = 'G[l]', 
             "w1" = 'omega[1]', "w2" = 'omega[2]', "w3" = 'omega[3]', "w4" = 'omega[4]', 
             "w5" = 'omega[5]', "Alpha" = 'alpha', "Beta" = 'beta', "Amin" = 'A[min]', 
             "dl" = 'd[l]', "df" = 'd[f]')

# and missing values
labels[which(sqrt(df$x^2 + df$y^2) < .5)] <- NA


p1 <- ggplot(data=df, aes(y=y, x=x, colour=Parameters)) + 
  geom_point() + scale_colour_discrete() +
  coord_cartesian(xlim=c(-2,3), ylim=c(-2,3)) + # causes overlapping
  geom_text(aes(label = labels), hjust=-0.3, vjust=1, 
            show_guide=FALSE, parse=TRUE) 

p1 # selected labels appear with correct expression


p2 <- direct.label(p1, method='smart.grid')
p2 # all labels appear (not wanted) without expression parsing

0 个答案:

没有答案