ggplot aes fill 没有明显原因无法工作

Ed2*_*122 2 r fill ggplot2 aesthetics

我已经制作了 ggplot 图形数百次(如果不是数千次),并且大约 99% 的时间使用 aes 将填充设置为基于 df 中的变量。由于某种原因,填充颜色不起作用(点每次都是黑色的),我不明白为什么,代码中没有任何明确的内容。我已经尝试了几乎所有我能想到的对代码的调整或调整,一次删除一个行或一个部分来测试哪个部分出错了。即使我只运行前两行,除了黑色之外我没有得到任何填充颜色。有什么想法吗?

ggplot(mean_score_by_type, aes(x = Inference, y = Direct, fill=as.factor(Age_Group))) +
  geom_point(alpha=0.7, size=4, stroke=1, position=position_jitter(width=0.05, height=0.05)) +
  scale_fill_discrete(name = "Age (Years)") +
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_y_continuous(breaks=seq(0,1,0.25), limits=c(0.25,1.05)) +
  labs(y="Direct", x="Inference", title="Proportion of Correct Responses") +
  geom_vline(xintercept=.56, color="red", linetype=2) + 
  geom_hline(yintercept=.56, color="blue", linetype=2) +
  facet_wrap(~Group)
Run Code Online (Sandbox Code Playgroud)

几行数据:

 Participant Age_Group Control-ID Control-MC Direct Inference   Group
        1         6      1.000      1.000     1.00      0.75 Under 7
        2         6      1.000      1.000     1.00      0.00 Under 7
        3         4      1.000      1.000     1.00      0.50 Under 7
        4         4      0.875      0.625     1.00      0.25 Under 7
        5         6      1.000      1.000     1.00      0.25 Under 7
        23        7      1.000      0.750     0.50      1.00  Over 7
        24        8      1.000      1.000     1.00      1.00  Over 7
        26        8      1.000      1.000     1.00      1.00  Over 7
        27        7      1.000      1.000     1.00      1.00  Over 7
        28        7      1.000      1.000     1.00      1.00  Over 7
Run Code Online (Sandbox Code Playgroud)

特别奇怪的部分是下面的代码工作得很好 - 代码对于形状规范是相同的。我不知道为什么填充颜色在添加形状后可以正常工作,但结果却是黑色,没有形状美感。

ggplot(mean_score_by_type, aes(x = Inference, y = Direct, fill=as.factor(Age_Group), shape=Group)) +
  geom_point(alpha=0.7, size=4, stroke=1, position=position_jitter(width=0.05, height=0.05)) +
  scale_shape_manual(values=c(21, 23)) +
  scale_fill_discrete(name = "Age (Years)") +
  guides(shape = FALSE, fill = guide_legend(override.aes = list(shape=c(21,21,21,23,23,23)))) +
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_y_continuous(breaks=seq(0,1,0.25), limits=c(0.25,1.05)) +
  labs(y="Direct", x="Inference", title="Proportion of Correct Responses") +
  geom_vline(xintercept=.56, color="red", linetype=2) + 
  geom_hline(yintercept=.56, color="blue", linetype=2)
Run Code Online (Sandbox Code Playgroud)

小智 6

您需要指定不同的字符类型。ggplot 选择的默认字符类型没有“填充”。如果您将pch = 21(或其他带有填充的类型)添加到 geom_point() 函数,这应该可以解决您的问题。

或者,您可以保留默认字符类型,然后指定color = as.factor(Age_Group)