2
votes

I'm new to R code, and I'm doing a plot exercise. I made dataframe test with 40 groups, and there are five members in each group, each member has a number, so the data would be like:

Group    Member1    Member2    Member3    Member4    Member5
1          10         13         7          8           9   
2          6          3          1          12          5
.
.
.
39         10        10          21         6           1
40         9         13          18         7           15

I want to plot bar chart for a specific row with all members, for example for group 20, I want to plot :

Group    Member1    Member2    Member3    Member4    Member5
20          5         7          12          29         4   

and I tried:

ggplot(test,aes(x=Group,y=Member1)) + geom_bar(data=subset(test,Group==20),'identity')

or

ggplot(subset(test,Group==20),aes(x=Group,y=Member1)) + geom_bar('identity')

both of them are incorrect, should I use factor() to make the column names be factors?
I was plotting sucu multiple column graph by using multiple +geom_line or geom_bar to put it together, but it won't be worked with specific row. I think I used the wrong method to do such problem. Any other nicer code and method to do that? Thanks for answering and sharing.

1

1 Answers

1
votes

First transform your data in long format with pivot_longer

Then mutate Member to factor

Then filter the desired group

then plot

library(tidyverse)
df1 <- df %>% 
  pivot_longer(cols = -Group,
               names_to = "Member",
               values_to = "value"
                 ) %>% 
  mutate(Member = as.factor(Member)) %>% 
  filter(Group == 1)

ggplot(data = df1, aes(x = Member, y=value)) +
  geom_bar(stat="identity", color="blue", fill="white")

data:

library(tidyverse)
df <- tribble(
  ~Group,    ~Member1,    ~Member2,    ~Member3,    ~Member4,    ~Member5,
1, 10, 13, 7, 8, 9, 
2, 6, 3, 1, 12, 5, 
39, 10, 10, 21, 6, 1, 
40, 9, 13, 18, 7, 15)

enter image description here

  • Alternative all groups
df2 <- df %>% 
  pivot_longer(cols = -Group,
               names_to = "Member",
               values_to = "value"
  ) %>% 
  mutate(Member = as.factor(Member),
         Group = as.factor(Group))
  
p<-ggplot(df2, aes(x=Member, y=value, fill=Group)) +
  geom_bar(position="dodge",stat="identity")+theme_minimal()
p

enter image description here