direct.label error on ggplot with single series to

2019-08-05 11:57发布

问题:

I am looking to resolve an error that I encounter when trying to use direct.label to label a ggplot with only one series. Below is a example to illustrate how direct.label fails if there is only a single series.

In my real data, I am looping through regions and wanting to use direct labels on the sub-regions. However, in my case some of the regions only have one sub-region resulting in an error when using direct.label. Any assistance would be greatly appreciated

library(ggplot2)
library(directlabels)
# sample data from ggplot2 movies data
mry <- do.call(rbind, by(movies, round(movies$rating), function(df) {
  nums <- tapply(df$length, df$year, length)
  data.frame(rating=round(df$rating[1]), year = as.numeric(names(nums)), number=as.vector(nums))
}))

# use direct labels to label based on rating
p <- ggplot(mry, aes(x=year, y=number, group=rating, color=rating)) + geom_line()
direct.label(p, "last.bumpup")


# subset to only a single rating
mry2 = subset(mry, rating==10)
p2 <- ggplot(mry2, aes(x=year, y=number, group=rating, color=rating)) + geom_line()
p2

# direct labels fails when attempting to label plot with a single series
direct.label(p2, "last.bumpup")

回答1:

This indeed was a bug; the package maintainer has already fixed it. To obtain an updated version,

install.packages("directlabels", repos="http://r-forge.r-project.org")

I've just checked, everything now runs fine. Nice catch!



标签: r ggplot2