首页 > 解决方案 > 在ggplot R中使用边框可自定义pch时,如何使geom_errorbar()与点的填充颜色相同?

问题描述

我使用特殊的 pch (21-25) 来制作散点图,ggplot因为我希望点的填充随因子水平而变化,但我也希望点的边界固定为黑色。我希望为每个点添加一个误差条,并且我希望误差条与点的填充颜色相同。但是,由于我将colour点的美感固定为黑色并geom_errorbar()使用它来绘制误差线的颜色,我似乎无法弄清楚如何获得我想要的结果。

这是一个简单的例子,我得到了不想要的结果(错误栏中的黑色):

library(ggplot2)
test <- cbind.data.frame(
  x = rnorm(10),
  y = rnorm(10),
  stdv = sd(rnorm(10)),
  fl = c(rep("foo", 5), rep("bar", 5))
)

ggplot(data = test, aes(x = x, y = y, colour = fl, fill = fl, ymin = y - stdv, ymax = y + stdv)) +
  geom_point(shape = 21, size = 3) +
  scale_colour_manual(values = rep("black", nrow(test))) +
  geom_errorbar()

例子

标签: rggplot2

解决方案


您可以尝试使用new_scale_color()from ggnewscalepackage (当然这是我从@AllanCameron学到的技巧):

library(ggplot2)
library(ggnewscale)
#Data
test <- cbind.data.frame(
  x = rnorm(10),
  y = rnorm(10),
  stdv = sd(rnorm(10)),
  fl = c(rep("foo", 5), rep("bar", 5))
)
#Plot
ggplot(data = test, aes(x = x, y = y,
                        colour = fl, 
                        fill = fl,
                        ymin = y - stdv,
                        ymax = y + stdv)) +
  geom_point(shape = 21, size = 3) +
  scale_colour_manual(values = rep("black", nrow(test))) +
  new_scale_color()+
  geom_errorbar(aes(color=fl))

输出:

在此处输入图像描述


推荐阅读