1

I'm trying to create a line from my Y point to Y=0 for each of my data points. My Y axis is "stat(count)", which seems to be creating problems when I add "geom_segment". This works to create my graph:

ggplot(my_data, aes(x = X, y = stat(count))) +    
theme_minimal() +   stat_count(geom = "point") +   
ylim(0,4) +   
scale_x_continuous(breaks = seq(0,457,50))

However, when I add in

  geom_segment(aes(xend=X, yend=0))

I get the following error:

"Error: Aesthetics must be valid computed stats. Problematic aesthetic(s): y = stat(count). Did you map your stat in the wrong layer?"

  • Can you provide a reproducible example of your dataset such as described in this link https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – dc37 Apr 20 '20 at 18:09
  • I don't understand your data, `X` is continuous? – Rui Barradas Apr 20 '20 at 18:15

1 Answers1

0

Wihtout having to use stat = "count" in ggplot2, you can calculate the count of each object outside of ggplot2 for example using count function from dplyr package:

Here, I simulate a X sequence of 10 different numbers with differnt count values:

library(dplyr)

df <- data.frame(x = sample(1:10,50,replace = TRUE))

df %>% count(x)

# A tibble: 10 x 2
       x     n
   <int> <int>
 1     1     4
 2     2     6
 3     3     2
 4     4    10
 5     5     4
 6     6     1
 7     7     9
 8     8     5
 9     9     5
10    10     4

Then, you can pass this count as your yend argument into geom_segment ofggplot2` as follow:

library(dplyr)
library(ggplot2)

df %>% count(x) %>%
  ggplot(aes(x = x))+
  geom_point(aes(y = n))+
  geom_segment(aes(xend = x, y=0, yend = n))

enter image description here

Is it what you are looking for ?

If not, can you provide a reproducible example of your dataset by using this link: How to make a great R reproducible example

dc37
  • 15,840
  • 4
  • 15
  • 32