Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

dodged geom_bar labels get mixed up when they are character labels #465

Closed
ashenkin opened this Issue · 2 comments

3 participants

@ashenkin

It seems that when text labels are used, dodged label positions get mixed up. See https://groups.google.com/group/ggplot2/browse_thread/thread/d9a86f13145d4650 for the discussion.

set.seed(121)
df = data.frame(class = c(1,1,2,2,3,3,4,4,5,5), val = round(runif(10),2), group = c("group1", "group2"))
df$text_labels = as.character(sprintf("%2.2f", df$val))

ggplot(data = df, aes(x=class, y=val, fill=group)) +
    geom_bar(stat="identity", position=position_dodge(width=1)) + 
    geom_text(aes(label = text_labels, y = val + 0.1), angle = 45,
        alpha = 0.5, position = position_dodge(width=1)) +
    geom_text(aes(label = val, y = val + 0.1), angle = 45, colour = "red",
        alpha=0.5, position = position_dodge(width=1))
@wch
Collaborator
wch commented

I think I found the source of the problem: the label column of the data is being treated as a grouping variable, when it shouldn't be.

Here's the relevant code from utilities-layer.r in 0.8.9. It explicitly ignores label:

  if (is.null(data$group)) {
    cat <- sapply(data[setdiff(names(data), "label")], is.discrete)
    cat <- intersect(names(which(cat)), .all_aesthetics)

    if (length(cat) == 0) {
      data$group <- 1
    } else {
      data$group <- as.numeric(interaction(data[cat]))
    }
  }

Here's the code in 0.9.0. It does not ignore label:

  if (is.null(data$group)) {
    disc <- vapply(data, is.discrete, logical(1))

    if (any(disc)) {
      data$group <- id(data[disc], drop = TRUE)      
    } else {
      data$group <- 1L
    }
  }

@hadley This change was made in 8267bf6. In that commit you edited the documentation and removed the part where it said, "... excluding label". Was there a reason for doing this? If not, then I think the solution is to add back the code to exclude label.

@wch wch referenced this issue from a commit in wch/ggplot2
@wch wch Don't use label as a grouping var (fix #465) 7994d5f
@hadley
Owner

Hmmm I don't know why I did that - maybe because it made the code look cleaner? I should have added a test :/

@wch wch closed this in 0ff6546
@kohske kohske referenced this issue from a commit in kohske/ggplot2
@wch wch Don't use label as a grouping var (fix #465) 1ca07de
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.