gdeniz
gdeniz

Reputation: 177

How to plot two subsets of a value column based on a factor column best in a scatter plot in ggplot?

I am wondering what's the simplest way to plot two subsets of a value column against each other (e.g. scatter plot with ggplot)? Example datframe =

Intensity Factor Order
1 red 1
2 red 2
3 red 3
1 green 1
3 green 2
5 green 3

Corresponding values are defined by the Order column. The goal would be to now plot corresponding red vs. green intensity values. Is there a simple way to do this in ggplot besides subsetting the dataframe into two beforehand?

Thanks for your insights.

Upvotes: 2

Views: 129

Answers (1)

akrun
akrun

Reputation: 887148

We can reshape to 'wide' format and then do the plot with geom_point

library(dplyr)
library(tidyr)
library(ggplot2)
library(data.table)
df1 %>% 
    mutate(rn = rowid(Factor)) %>%
    pivot_wider(names_from = Factor, values_from = Intensity) %>% 
    select(-rn) %>% 
    ggplot(aes(x = red, y = green)) + 
          geom_point()

-output enter image description here

data

df1 <- structure(list(Intensity = c(1L, 2L, 3L, 1L, 3L, 5L), Factor = c("red", 
"red", "red", "green", "green", "green")), class = "data.frame", 
row.names = c(NA, 
-6L))

Upvotes: 3

Related Questions