Alfredo Sánchez
Alfredo Sánchez

Reputation: 735

Discrete frequency polygon over a bar plot

I want to draw a frequency polygon over a bar plot with ggplot2. I use the commands below

library(ggplot2)
g <- ggplot(diamonds) + geom_bar(aes(cut))
g + geom_freqpoly(aes(as.numeric(cut)),binwidth=1)

but the polygon vertices are not on the center of the bars. I tried different binwidth without success.

Upvotes: 2

Views: 959

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98429

You should remove as.numeric() from aes() and then add group=1 inside aes() to ensure that points are connected by line.

ggplot(diamonds) + geom_bar(aes(cut))+
          geom_freqpoly(aes(cut,group=1))

Or simply

ggplot(diamonds,aes(cut,group=1)) + geom_bar()+
          geom_freqpoly()

enter image description here

Upvotes: 2

Related Questions