Revan
Revan

Reputation: 2322

Plot frequency table of vector in ggplot

I have created a frequency of the values of a vector with the table function and plotted the distribution (over a length of 10).

x <- c(1,3,5,5,6)

plot(table(x), type = "p", pch = 20, xlim = c(1, 10), axes = FALSE)
axis(side = 1, at = c(seq(0, 10, by = 1)))
axis(side = 2)

How can I make this plot with ggplot?

If I create a data frame from the table function, the x axis is not scaled properly (instead the values on the x axis are categorical).

library(ggplot2)

ggplot(as.data.frame(table(x)), aes(x, Freq)) +
  geom_point()

Any ideas how to solve this?

Upvotes: 0

Views: 1532

Answers (1)

GGamba
GGamba

Reputation: 13680

table(x) returns x as a factor, you will have to cast it back to numeric for the scale to be continuous.

ggplot(as.data.frame(table(x))) + 
    geom_point(aes(x = as.numeric(as.character(x)), 
                   y = Freq)) + 
    scale_x_continuous()

Or you can let ggplot2 do the calculation for you:

ggplot(as.data.frame(x)) +
    geom_point(aes(x = x), stat = 'count')

enter image description here

Upvotes: 3

Related Questions