Home > Mobile >  Why does adding aethetics to my ggplot cause an error?
Why does adding aethetics to my ggplot cause an error?

Time:04-20

I made a simple bar chart showing the mean and standard deviation of two columns of a csv. The standard plot output is very ugly so I wanted to make some changes, but I can seem to get it to work.

For example, say the csv looks like this.

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

Then

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

Gives this plot here. Functional, but ugly. Ugly Plot

So I decided to start with a colour change

p1   geom_bar(fill = "red")

Which throws an error which I don't understand and breaks the plot.

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

CodePudding user response:

The columns are already being drawn by your first stat_summary call, which is where you need to apply your fill. If you want to map the color to the x axis variable you can do something like this:

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

enter image description here

Or if you want just a single color you can do:

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

enter image description here

  • Related