Krutik
Krutik

Reputation: 501

How to plot lines and dots in the same plot while using different sized data

This toy data frame represents my data.

        Time    Gene     Value
   1      0      A         1
   2      1      A         2
   3      2      A         3
   4      0      B         1 
   5      1.2    B         2 
   6      1.7    B         2 
   7      2.1    B         2 
   8      3      B         2

Using the following code I can turn this into a line plot with two lines, one for A and one for B.

ggplot(data=Data, aes(x=Time, y=Value, group=Gene)) +
geom_line(aes(color=Gene), linetype="longdash", size=2)+
theme_classic()+
labs(title= paste("Genes over time course"),
     x="Time",
     y="Expression")+
theme(plot.title=element_text(size=20, face="bold",hjust = 0.5), 
      axis.text.x=element_text(size=10), 
      axis.text.y=element_text(size=10),
      axis.title.x=element_text(size=15),
      axis.title.y=element_text(size=15),
      legend.text=element_text(size=10))

However, I would like Gene A to be represented by only dots, and Gene B to be represented by only a line. How can I accomplish this given the data?

Upvotes: 1

Views: 236

Answers (1)

r2evans
r2evans

Reputation: 160492

Using data=~subset(., ...) we can control which data goes to each layer.

ggplot(Data, aes(x = Time, y = Value, color = Gene, group = Gene)) +
  geom_line(data = ~ subset(., Gene != "A")) +
  geom_point(data = ~ subset(., Gene == "A"))

ggplot geom points and lines

(You can also use dplyr::select in place of subset, the results are the same.)

Upvotes: 2

Related Questions