简体   繁体   English

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

[英]How to make geom_errorbar() the same color as the fill of points when using border customizable pch in ggplot R?

I'm using the special pch (21-25) to make a scatter plot with ggplot since I want the fill of the points to vary with factor levels, but I also want the border of the points to be fixed as black.我使用特殊的 pch (21-25) 用 ggplot 制作散布ggplot因为我希望点的填充随因子水平而变化,但我也希望点的边界固定为黑色。 I wish to add an error bar to each of the points and I want the error bar to be the same color as the fill of the points.我希望为每个点添加一个误差条,并且我希望误差条与点的填充颜色相同。 However, since I'm fixing the colour aesthetic of points to black and geom_errorbar() uses this to plot the color of the error bars I can't seem to figure out how to get the result I want.但是,由于我将点的colour美学固定为黑色,并且geom_errorbar()使用它来 plot 错误条的颜色,我似乎无法弄清楚如何获得我想要的结果。

Here is a simple example where I'm getting the undesired result (black color in the error bars):这是一个简单的例子,我得到了不想要的结果(错误栏中的黑色):

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()

例子

You can try with new_scale_color() from ggnewscale package (for sure this a trick I learnt from @AllanCameron ):您可以尝试使用 ggnewscale package 中的new_scale_color() (当然这是我从ggnewscale学到的技巧):

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))

Output: Output:

在此处输入图像描述

Any reason you're using scale_colour_manual() instead of just using colour = "black" ?您使用scale_colour_manual()而不是仅使用colour = "black"的任何原因? If your actual example allows you to use that, then, you don't need ggnewscale:如果您的实际示例允许您使用它,那么您不需要 ggnewscale:

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, colour = "black") +
  geom_errorbar()

Created on 2020-12-11 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2020 年 12 月 11 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM