哪个相当于ggplot中的seaborn hue?
Which is the equivalen to seaborn hue in ggplot?
我开始用 R 编程,但我被困在了这个情节中。
这是我打算制作的情节:
我可以用这段代码来完成:
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")
我需要使用 ggplot 来完成它,因为我必须添加进一步的格式,但我没有找到这样做的方法,我正在寻找 seaborn 上 "hue" 函数的等价物.
sns.catplot(x="sex", y="survived", hue="class", kind="point", data=titanic);
一种方法是分别创建两个数据帧
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")
要使用ggplot2
,最好准备一个包含所有值的数据框。此外,建议使用 "long-format" 数据框。然后我们可以将颜色映射到 class
,在您的示例中是 y
和 z
。
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())
我开始用 R 编程,但我被困在了这个情节中。 这是我打算制作的情节:
我可以用这段代码来完成:
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")
我需要使用 ggplot 来完成它,因为我必须添加进一步的格式,但我没有找到这样做的方法,我正在寻找 seaborn 上 "hue" 函数的等价物.
sns.catplot(x="sex", y="survived", hue="class", kind="point", data=titanic);
一种方法是分别创建两个数据帧
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")
要使用ggplot2
,最好准备一个包含所有值的数据框。此外,建议使用 "long-format" 数据框。然后我们可以将颜色映射到 class
,在您的示例中是 y
和 z
。
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())