CODEX

How can I produce an effective scientific figure in R? ggplot2 barplot.

Julian Willett, MD
Jan 16 · 4 min read
Image for post
Image for post

Introduction:

library(ggplot2)
#Below is how to produce the data frame using vectors
names = c('Bob','Oscar','Helen','Cindy','Bob')
sexes = c('Male','Male','Female','Female','Male')
df = data.frame("Name"=names, "Sex"=sexes)
#Below is how to produce the data frame without using vectors
df = data.frame("Name"=c('Bob','Oscar','Helen','Cindy','Bob'),
"Sex"=c('Male','Male','Female','Female','Male'))
#editing the data frame entry at a particular cell. The first bracket is accessing the first column with a double bracket denoting you want to access the actual internal vector. This does not work with a single bracket. The second bracket is accessing the second row. A double bracket is not needed for the second bracket as there is only one item to access versus a list.
>df[[1]][2]
[1] "Oscar"
>df[[1]][2] = 'Ron'
>df[[1]][2]
[1] "Ron"
>df[1]
Name
1 Bob
2 Oscar
3 Helen
4 Cindy
5 Bob
>df[[1]]
[1] "Bob" "Oscar" "Helen" "Cindy" "Bob"
>df[1][2]
Name
1 Bob
2 Oscar
3 Helen
4 Cindy
5 Bob
>df[[1]][2]
[1] "Oscar"
>df[[1]][[2]]
[1] "Oscar"
#editing the vector
>names[2]
[1] "Oscar
>names[2] = 'Ron'
>names[2]
[1] "Ron"
q = df %>% ggplot(aes(x=Name,fill=Sex)) + geom_bar()
## OR
q = ggplot(df,aes(x=Name,fill=Sex)) + geom_bar()
Image for post
Image for post
Image for post
Image for post

Summary:

CodeX

Everything connected with Code & Tech!

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store