【问题标题】:Adding extra geom_point with differect scales添加具有不同比例的额外 geom_point
【发布时间】:2020-08-13 18:46:15
【问题描述】:

我正在尝试在geom_point 之上添加另一组点。问题是初始数据集有一个具有 3 个级别的因子,而第二个没有。我希望第一组点根据因子水平具有不同的颜色和形状,第二组点是统一的。剧情是这样的:

plot = ggplot() +
  geom_point(data1, 
              aes(x = x1, y = y1, 
              color = factor, shape = factor)) +
  scale_color_manual(values = factor_color) +
  scale_shape_manual(values = factor_shape)

当我添加另一组点时,

plot +
geom_point(data2, 
           aes(x = x2, y = y2))

我收到此错误

错误:手动刻度中的值不足。需要 4 个,但只有 3 个 提供。

我明白为什么会这样。 但是当我在第二个geom_pointcolor = "red"shape = 1 中设置刻度时,我得到了这个错误

错误:提供给离散刻度的连续值

这个问题有解决办法吗?

编辑

示例数据具有这种结构

data1 = data.frame(factor = factor(rep(letters[1:3], 3)),
                   x1 = rnorm(9),
                   y1 = rnorm(9))

data2 = data.frame(x2 = rnorm(6),
                   y2 = rnorm(6))

factor_color = scales::hue_pal()(3)
factor_shape = c(19, 15, 17)

【问题讨论】:

  • 您好 Katerina,当您发布问题时,您应该始终提供可重现的示例。在这种情况下,您的数据丢失。你应该提供一个模拟或类似的东西。寻找“可重现的例子”
  • 我在第二个geom_point 中添加了美学内的刻度。当我拿出来时它起作用了。感谢您的帮助!
  • 嗨@KaterinaSym。欢迎来到堆栈溢出。我不确定你是否知道该怎么做when someone answers your question。另外,作为新用户,访问 Stack Overflow 的help center 是有益的。祝你有美好的一天!

标签: r ggplot2


【解决方案1】:

在我的例子中,我没有错误。

刚刚猜到你的数据:

data1 <- data.frame(factor = factor(letters[1:4]),
                    x1 = rnorm(4),
                    y1 = rnorm(4))
data2 <- data.frame(factor = factor(letters[1:3]),
                    x2 = rnorm(3),
                    y2 = rnorm(3))

factor_color <- scales::hue_pal()(4)
factor_shape <- 1:4

您的代码有两个小改动。 我在geom_point 中都指定了data =

library(ggplot2)

plot <- ggplot() +
  geom_point(data = data1, 
             aes(x = x1, y = y1, 
                 color = factor, shape = factor)) +
  scale_color_manual(values = factor_color) +
  scale_shape_manual(values = factor_shape)


plot +
  geom_point(data = data2, 
             aes(x = x2, y = y2))

【讨论】:

    猜你喜欢
    • 2022-07-06
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多