Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change legend labels in ggplot2 for visualizing data in R? [duplicate]

My code is like below, I want to change the label of the ggplot, but R always remind me:

Error in unit(tic_pos.c, "mm") : 'x' and 'units' must have length > 0

What should I do?

ggplot(mat,aes(x=sales,col=type))+
  geom_density()+labels("red_sold","blue_sold","yellow_sold")
like image 607
Chen Avatar asked Dec 03 '25 14:12

Chen


1 Answers

Is mat$type a factor? If not, that will cause the error. Also, you can't use labels(...) this way.

Since you did not provide any data, here's an example using the built-in mtcars dataset.

ggplot(mtcars, aes(x=hp,color=factor(cyl)))+
  geom_density()+
  scale_color_manual(name="Cylinders",
                       labels=c("4 Cylinder","6 Cylinder","8- Cylinder"),
                       values=c("red","green","blue"))

In this example,

ggplot(mtcars, aes(x=hp,color=cyl))+...

would cause the same error that you are getting, because mtcars$cyl is not a factor.

like image 106
jlhoward Avatar answered Dec 05 '25 06:12

jlhoward



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!