1

I'm starting to program in R and I'm getting stuck in this plot. This is the plot I'm traying to make:

enter image description here

I'm able to do it with this code:

x <- seq(0, 10,1 )
y = x**2
z= x**3
plot(x, y, type="o", col="blue",xlab='x',ylab="y = x2")
lines(x,z,col="green")

I need to do it ussing ggplot, since I have to add futher formating, but I'm not finding the way to do it, I'm loking for the equivalen of the "hue" function on seaborn.

sns.catplot(x="sex", y="survived", hue="class", kind="point", data=titanic);
Luis Ramon Ramirez Rodriguez
  • 9,591
  • 27
  • 102
  • 181

2 Answers2

1

One way would be creating two dataframes separately

library(ggplot2)

df1 <- data.frame(x, y)
df2 <- data.frame(x, z)

ggplot(df1, aes(x, y)) + 
       geom_line(color = "blue") + 
       geom_point(color = "blue", shape = 1, size = 2) + 
       geom_line(data = df2, aes(x, z), color = "green") +
       ylab("y = x2")

enter image description here

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

To use ggplot2, it is better to prepare a data frame with all the values. Furthermore, it is recommended to work with "long-format" data frame. We can then map the color to class, which is y and z in your example.

x <- seq(0, 10,1 )
y <- x**2
z <- x**3

# Load the tidyverse package, which contains ggplot2 and tidyr
library(tidyverse)

# Create example data frame
dat <- data.frame(x, y, z)

# Conver to long format
dat2 <- dat %>% gather(class, value, -x)

# Plot the data
ggplot(dat2, 
       # Map x to x, y to value, and color to class
       aes(x = x, y = value, color = class)) + 
  # Add point and line
  geom_point() +
  geom_line() +
  # Map the color as y is blue and z is green
  scale_color_manual(values = c("y" = "blue", "z" = "green")) +
  # Adjust the format to mimic the base R plot
  theme_classic() +
  theme(panel.grid = element_blank())

enter image description here

www
  • 38,575
  • 12
  • 48
  • 84