I have looked at possible previous questions about this, and I have found this one: Error in FUN(X[[i]], ...) : object not found when adding geom_text with facet, and unfortunately, I must be too much of a beginner, since I could not solve the issue.
Therefore, I ask here, hoping that somebody will tell me how to do it...
I use the diamonds dataset from R to get a density plot, either with fill=clarity or fill=cut. It works fine.
When I try to add text, I get errors, different errors depending on whether it is "cut" or "clarity" I use on the fill, by the way.
I read in the mentioned answer that I have to merge the datasets.
How do I do that?
The diamonds dataset has a great many rows, and the text dataset only a few.
Here is the code:
if (!require("tidyverse")) install.packages("tidyverse", dependencies = TRUE)
library("tidyverse")
diams2 <-diamonds
annot2 <- data.frame(
text = c("IF", "WS1", "WS2", "VS1", "VS2", "SI1", "SI2", "I1"),
xx = c( 10, 20, 30, 40, 50, 60, 70, 80),
yy = c( 5, 10, 15, 20, 25, 30, 35, 40)
)
# THIS RUNS FINE:
diams2 %>%
ggplot(aes(x=price, fill=cut))+
geom_density(adjust=1.5, position = "stack")+
theme_void()
# THIS RUNS FINE:
diams2 %>%
ggplot(aes(x=price, fill=clarity))+
geom_density(adjust=1.5, position = "stack")+
theme_void()
# THIS WON'T RUN, AND GIVES THE FOLLOWING ERROR MESSAGE:
# Don't know how to automatically pick scale for object of type function. Defaulting to continuous.
# Error in `f()`:
# ! Aesthetics must be valid data columns. Problematic aesthetic(s): fill = cut.
# Did you mistype the name of a data column or forget to add after_stat()?
diams2 %>%
ggplot(aes(x=price, fill=cut))+
geom_text(data=annot2,
aes(x=x, y=y, label=text,
color=text), hjust=0, size=4)+
geom_density(adjust=1.5, position = "stack")+
theme_void()
# THIS WON'T RUN, AND GIVES THE FOLLOWING ERROR MESSAGE:
# Error in FUN(X[[i]], ...) : object 'clarity' not found
diams2 %>%
ggplot(aes(x=price, fill=clarity))+
geom_text(data=annot2,
aes(x=x, y=y, label=text,
color=text), hjust=0, size=4)+
geom_density(adjust=1.5, position = "stack")+
theme_void()
Thank you!