为什么将美学添加到我的 ggplot 会导致错误?

Why does adding aethetics to my ggplot cause an error?

我制作了一个简单的条形图,显示了 csv 两列的平均值和标准差。标准绘图输出非常难看,所以我想做一些更改,但我似乎可以让它工作。

例如,假设 csv 看起来像这样。

unfiltered_data,filtered_data
2,1
3,4
5,6
7,8

然后

test <- read.csv("Performance Metric Testing/test.csv")

long <- tidyr::pivot_longer(test, everything(), names_to = "data")
p1 <- ggplot(long, aes(data, value)) + 
  stat_summary(fun = "mean", geom = "col") +
  stat_summary(fun.data = "mean_se")
p1

在这里给出这个情节。实用,但丑陋。

所以我决定从换色开始

p1 + geom_bar(fill = "red")

抛出一个我不理解的错误并破坏了情节。

Error in `f()`:
! stat_count() can only have an x or y aesthetic.
Run `rlang::last_error()` to see where the error occurred.

您的第一个 stat_summary 调用已经绘制了这些列,您需要在此处应用填充。如果你想将颜色映射到 x 轴变量,你可以这样做:

ggplot(long, aes(data, value)) + 
  stat_summary(fun = "mean", geom = "col", aes(fill = data)) +
  stat_summary(fun.data = "mean_se") +
  scale_fill_manual(values = c("red", "blue"))

或者如果您只想要一种颜色,您可以这样做:

ggplot(long, aes(data, value)) + 
  stat_summary(fun = "mean", geom = "col", fill = "red") +
  stat_summary(fun.data = "mean_se")