ordered factors in ggplot2 bar chart

后端 未结 1 1441
感动是毒
感动是毒 2020-12-10 21:40

I have a data frame with (to simplify) judges, movies, and ratings (ratings are on a 1 star to 5 star scale):

d = data.frame(judge=c(\"alice\",\"bob\",\"alic         


        
相关标签:
1条回答
  • 2020-12-10 21:56

    I'm not sure your sample data frame is representative of the images you put up. You mentioned your ratings are on a 1-5 scale, but your images show a -3 to 3 scale. With that said, I think this should get you going in the right direction:

    Sample data:

    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))
    

    You were closest with this:

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

    and by adjusting the default binwidth in geom_bar we can make the bar widths more appropriate and treating rating as a factor centers them over the label:

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

    alt text

    If you wanted to incorporate one of the other variables in the chart such as the movie, you can use fill:

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

    alt text

    It may make more sense to put the movies on the x axis and fill with the rating if you have a small number of movies to compare:

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

    If this doesn't get you on your way, put up a more representative example of your dataset. I wasn't able to recreate the ordering problems, but that could be due to a difference in the sample data you posted and the data you are analyzing.

    The ggplot website is also a great reference: http://had.co.nz/ggplot2/geom_bar.html

    0 讨论(0)
提交回复
热议问题