I am plotting a barplot using ggplot + geom_bar() function in R.

I have some the recoreds which share the same x-axis identifiers.

geom_bar() did merge all values that shared the same x-axis identifiers.

Like the following example.


df <- data.frame(x = c("a","a","b","c","d","e"),
                 y = c(5,5,5,5,5,5),
                 stringsAsFactors = FALSE)

ggplot(df, aes(x, y)) + geom_bar(stat = "identity")

The erroneous graph is displayed below.

The highest bar means the sum of multiple y-values shared same x-axis names.

Anyone else could help me to solve this problem? Thanks.

enter image description here

  • $\begingroup$ Please provide a reproducible example so we can understand what's going on. $\endgroup$
    – Ram RS
    Dec 20 '20 at 7:20
  • $\begingroup$ Interesting question. Your data is out of shape though - you cannot plot duplicate data points on an axis - how will anyone reading the plot know the difference between the two data points? $\endgroup$
    – Ram RS
    Dec 20 '20 at 20:30
  • $\begingroup$ Finally, I solved it using barplot() function that does not merge values that have same x-axis name. $\endgroup$
    – YP CHEN
    Dec 21 '20 at 2:34

As you seem to have surmised, the graph is not erroneous, but correct. You have a total of 10 for a and that's what it's showing. If you want it to ignore duplicate X-axis values then you need to tell ggplot which datapoints it should actually be using. barplot() is assuming that your duplicate a values are intentional, ggplot assumes they should be grouped. These are both reasonable assumptions and it's your responsibility to determine beforehand which is correct.


Not the answer you're looking for? Browse other questions tagged or ask your own question.