在 ggplot2 上从多个数据帧创建复杂的自定义图形

问题描述 投票:0回答:1

我正在开发一个项目,我需要使用 R 中的 ggplot2 将两个不同数据帧的数据组合成一个图。我想知道如何有效地实现这一点,为图中的每个数据集分配特定的特征。

我有两个数据框,每个数据框都有不同的变量。我想在单个图表上叠加 df1 和 df2 的绘图,同时为每个数据集自定义绘图功能,例如颜色、形状和标签。

我希望我的绘图具有两个背景椭圆,一个为紫色,另一个为绿色,以及每个椭圆的质心。这些椭圆是使用

stat_ellipse
和来自
df2
的数据生成的。在前景中,我希望
df1
中的点可见,但具有以下脚本中指定的颜色渐变:

# Create data frame df1
df1 <- data.frame(
  x = c(1, 2, 3, 4, 5),
  y = c(2, 4, 3, 6, 5),
  color = runif(5, 0, 1))


# Create data frame df2
df2 <- data.frame(
  x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
  y = rnorm(10),
  group = rep(c('A', 'B'), each = 5))

要创建绘图,我不确定信息是否应该直接进入“ggplot()”代码,或者进入“geom_point”和“stat_ellipse”。不管怎样,我不确定如何单独调整绘图的每个组件的颜色。

plotGG <- ggplot() +
  stat_ellipse(data = df2, aes(x = x, y = y, color = group)) + #i want those ellipses purple and green
  geom_point(data = df1, aes(x = x, y = y, color = color), size = 3) +
  scale_color_gradient2(midpoint=0.5,low="#ba1414ff",mid = "#f3f3b9ff",high="#369121ff") #this is the color pallete that i want for the geom_points

我已经进展到这一点,但它会以某种方式产生错误。 预先感谢您!

r ggplot2 customization multiple-databases palette
1个回答
0
投票

在香草

ggplot2
中,您只能根据审美有比例(而您想要两种不同的色标),并且该比例是离散的或连续的(而您想要离散和连续的色标)。

但是实现您想要的结果的一个选择是

ggnewscale
包,它允许多种尺度以获得相同的美感:

set.seed(123)

# Create data frame df1
df1 <- data.frame(
  x = c(1, 2, 3, 4, 5),
  y = c(2, 4, 3, 6, 5),
  color = runif(5, 0, 1)
)

# Create data frame df2
df2 <- data.frame(
  x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
  y = rnorm(10),
  group = rep(c("A", "B"), each = 5)
)

library(ggplot2)
library(ggnewscale)

ggplot() +
  stat_ellipse(
    data = df2,
    aes(x = x, y = y, color = group)
  ) +
  scale_color_manual(
    values = c(A = "purple", B = "green")
  ) +
  ggnewscale::new_scale_color() +
  geom_point(
    data = df1,
    aes(x = x, y = y, color = color), size = 3
  ) +
  scale_color_gradient2(
    midpoint = 0.5,
    low = "#ba1414ff", mid = "#f3f3b9ff", high = "#369121ff"
  )

© www.soinside.com 2019 - 2024. All rights reserved.