Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: A continuous variable can not be mapped to shape [duplicate]

Tags:

r

ggplot2

I have the following sample code:

df <- data.frame(name = c("a", "b", "c"),
                 date = as.Date(c("2020-01-01", "2020-01-03", "2020-01-05")),
                 pch = c(18, 19, 1))

ggplot(data = df, aes(x = date, y = name)) + 
  geom_point(aes(shape = pch)) 

I would like to use the shapes 18, 19 and 1 (just as specified in the column pch of my data). Unfortunately, when I have numeric values in the column pch I get the message "A continuous variable can not be mapped to shape", but when I convert them into a factor I dont get the shapes I want because ggplot assigns the shapes automatically to my factor levels. What can I do?

like image 869
D. Studer Avatar asked Nov 24 '25 05:11

D. Studer


1 Answers

Maybe try this:

library(ggplot2)
#Code
ggplot(data = df, aes(x = date, y = name)) + 
  geom_point(aes(shape = factor(pch)))+
  scale_shape_manual(values=df$pch)+
  labs(shape='pch')

Output:

enter image description here

Or this:

#Code 2
ggplot(data = df, aes(x = date, y = name)) + 
  geom_point(aes(shape=pch))+
  scale_shape_identity()

Output:

enter image description here

It is also possible to avoid all wordy code with next solution using the I() function (Many thanks and credit to @teunbrand):

#Code 3
ggplot(data = df, aes(x = date, y = name)) + 
  geom_point(aes(shape = I(pch))) 

Same output.

like image 62
Duck Avatar answered Nov 26 '25 20:11

Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!