Ordered factors in the ggplot2 histogram

I have a data frame with (to simplify) judges, films and ratings (ratings refer to a scale from 1 star to 5 stars):

d = data.frame(judge=c("alice","bob","alice"), movie=c("toy story", "inception", "inception"), rating=c(1,3,5))

I want to create a histogram where the x axis is the number of stars, and the height of each bar is the number of ratings with this star.

If i do

ggplot(d, aes(rating)) + geom_bar()

this works great, except that the bars are not centered on each rating, and the width of each bar is not perfect.

If i do

ggplot(d, aes(factor(rating))) + geom_bar()

the order of the number of stars is confused with the x axis. (On my Mac, at least for some reason, the default ordering works on a Windows machine.) Here's what it looks like: alt text

I tried

ggplot(d, aes(factor(rating, ordered=T, levels=-3:3))) + geom_bar()

but that doesn't seem to help.

How can I make my histogram look like the image above, but with the correct x-axis ordering?

+3
1

, , . , 1-5, -3 3. , :

:

d = data.frame(judge=sample(c("alice","bob","tony"), 100, replace = TRUE)
    , movie=sample(c("toy story", "inception", "a league of their own"), 100, replace = TRUE)
    , rating =  sample(1:5, 100, replace = TRUE))

:

ggplot(d, aes(rating)) + geom_bar()

, geom_bar, , :

ggplot(d, aes(x = factor(rating))) + geom_bar(binwidth = 1)

alt text

, ​​ , fill:

ggplot(d, aes(x = factor(rating), fill = factor(movie))) + geom_bar(binwidth = 1)

alt text

, , :

ggplot(d, aes(x = factor(movie), fill = factor(rating))) + geom_bar(binwidth = 1)

, . , , , , .

ggplot : http://had.co.nz/ggplot2/geom_bar.html

+4

Source: https://habr.com/ru/post/1762750/


All Articles