1

我想使用 ggplot 来显示点和线,但我希望有两个图例 - 一个用于点,一个用于线。

我设法使用下面的代码做到了这一点,但由于某种原因,geom_point 中的“大小”选项不再响应,并且它们被困在您可以在图像中看到的相当丑陋的大小上

请注意,我选择 stroke = NA 因为我不希望这些点有边框。代码如下。

有任何想法吗?

ggplot(data = plot_data) +
    geom_point(aes(x = z.1, y = obs, fill = treatcat), alpha = 0.4, shape = 21, stroke = NA, size = 1) +
    geom_line(aes(x = z.1, y = under, colour = "True"), linetype = "dashed") +
    geom_line(aes(x = z.1, y = crude, colour = "Crude"), size = 1.5) +
    scale_fill_manual(name = "Treatment",
                        values = c("0" = "#F8766D", "1" = "#C77CFF"),
                        breaks = c("0", "1"),
                        labels = c("Untreated", "Treated")) + 
    scale_colour_manual(name = "Model",
                        values = c("Crude" = "orange", "True" = "black"),
                        breaks = c("Crude", "True"),
                        labels = c("Crude", "True")) + 
    ylim(-30,27.5) +
    theme(plot.title = element_text(size = "12")) +
    labs(title = "Fitted Values for Crude Model", x = "Z", y = "Y(1)")
4

2 回答 2

0

也许你想要两个色阶,这里有一个 ggnewscale 的解决方案。有几个具有类似功能的 github 包即将出现(relayer 和 ggh4x),但目前据我所知,这是唯一的 CRAN 选项。

根据评论 - 我正在使用 see::geom_point2 因为我也不喜欢那些笔画

library(ggplot2)
library(see)

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point2(aes(color = Petal.Width), alpha = 0.4, size = 10) +
  ggnewscale::new_scale_color() +
    geom_smooth(aes(color = Species), linetype = "dashed", method = "lm") 
于 2021-02-15T11:24:45.067 回答
0

目前,ggplot2 中存在一个错误,导致无法更改size一次stroke = NAhttps://github.com/tidyverse/ggplot2/issues/4624)。显然,设置“stroke = 0”也不会消除边框。

要执行您想要的操作,您需要将设置颜色设置为“透明”:

library(ggplot2)
df = data.frame(x=rnorm(100), y=rnorm(100))
ggplot(df, aes(x, y)) + geom_point(shape=21, stroke=0, fill="orange", color="transparent", size=8)

reprex 包于 2021-09-20 创建(v2.0.1)

于 2021-09-20T19:40:40.140 回答