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

ashenkin opened this Issue Apr 3, 2012 · 2 comments


None yet
3 participants

ashenkin commented Apr 3, 2012

It seems that when text labels are used, dodged label positions get mixed up. See for the discussion.

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 commented Apr 4, 2012

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 added a commit to wch/ggplot2 that referenced this issue Apr 4, 2012

@wch wch Don't use label as a grouping var (fix #465) 7994d5f

hadley commented Apr 4, 2012

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

wch closed this in 0ff6546 Apr 6, 2012

@kohske kohske added a commit to kohske/ggplot2 that referenced this issue Apr 27, 2012

@wch @kohske wch + kohske 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