0

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?

1
  • You can use as.numeric(x) rather than x in the aes, and the scale will be continuous. Commented Mar 31, 2017 at 7:19

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.