1
votes

I have a bar chart with x axis labels grouped by 2 column values. In the plot I want to show one column (method) values as legend and mark the other (variable) as labels on the plot itself for an easy to read picture. However each label on graph is repeated due to the grouping by the other column. How can I have a single label for a unique value instead of repeating it.?

Sample data and current output is below.

df <- data.table(w = rep(1:3, each = 3), 
        value = c(1.83,1.83,1.94,1.78,.95,1.09,3.14,3.14,3.14),
        method = seq(letters[1:3]),
        variable = c("fit","fit","fit","lwr","lwr","lwr","upr","upr","upr"))
ggplot(df,aes(x=w, y=value, color=factor(variable), fill=factor(method))) +
        geom_bar(stat="identity", position = "dodge") +
        geom_text(aes(label=paste(variable)), position = position_dodge(width =0.9),vjust=-.25) +
        theme_bw() +
        scale_y_log10(breaks=c(1,2,11,101,1001),labels=c(0,1,10,100,1000)) +
#       facet_wrap(~ppm) +
        annotation_logticks(sides = "lr")

enter image description here

1
If I understand you correctly, you want the labels on the graph to be variable and the labels in the legend to be from 'method', correct?black_sheep07

1 Answers

3
votes

I'm fond of saying ggplot2 is very good at plotting the data you give it. The variable you are using as the label has the repetition that is being plotted:

variable<-c("fit","fit","fit","lwr","lwr","lwr","upr","upr","upr")

If you don't want that repetition, create a variable without it for use as the label:

 df$label = ifelse(df$method == "b", as.character(df$variable), NA)

Then use aes(label = label) in your geom_text() call.

I would also recommend against using both fill and color mapped to different variables in a bar chart, but that's up to you. At the very least, if you define the color mapping in the geom_text() layer instead of in the plot initialization the bars won't have the clashing color outline.