HertieDataScience / SyllabusAndLectures

Hertie School of Governance Introduction to Collaborative Social Science Data Analysis
MIT License
37 stars 60 forks source link

Questions on grouped bar plot using ggplot2 (windows R.3.2.2) #77

Closed bctclc closed 8 years ago

bctclc commented 8 years ago

Hi everyone!

I tried to plot grouped bar char using ggplot2 and this is my code:

ggplot(as.data.frame(meanagetable), aes(factor(POfactor), agemean, fill = Agegroupl)) + 
        geom_bar(stat="identity", position = "dodge") +
        scale_fill_manual(labels=c("young people", "middle-age people", "elder people"), 
                            values=c("dodgerblue", "blue", "dodgerblue4")) +
        scale_x_discrete(limits=c("recharge", "battery", "cost", "knowledge", "spec", 
                                  "choice","technology", "safety", "resale")) +
        xlab("Factors putting off buying EVs") +
        ylab("% of respondents") +
        labs(fill="  ") +
        theme(panel.grid =element_blank())

It worked out ok, but I want to make two changes, but I'm sure what to do. 1) make the y axis tidier by imposing the interval of 0.1 2) unorder the three bars within each group.

rplot

Thank you!

christophergandrud commented 8 years ago

It looks like your y-axis variable may be entered as a factor. Try making sure it is numeric. Also, you can round the variable before plotting. Another thing to try would be to use the ggplot2 scale_y_continuous function which allows you to specify breaks and tick labels.

Regarding the second one, perhaps try turning the grouping variable into a factor with levels in order that you want the bars to be.

bctclc commented 8 years ago

Both worked out. Thank you very much!

christophergandrud commented 8 years ago

Great!