如何在ggplot中更改标签(图例)?

时间:2014-04-18 20:35:59

标签: r math plot ggplot2 statistics

我的代码如下,我想更改ggplot的标签,但R总是提醒我:

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

我该怎么办?

ggplot(mat,aes(x=sales,col=type))+
  geom_density()+labels("red_sold","blue_sold","yellow_sold")

2 个答案:

答案 0 :(得分:6)

mat$type是一个因素吗?如果没有,那将导致错误。此外,您无法以这种方式使用labels(...)

由于您未提供任何数据,因此以下是使用内置mtcars数据集的示例。

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

在此示例中,

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

会导致您获得相同的错误,因为mtcars$cyl不是一个因素。

答案 1 :(得分:1)

{@ {1}}是对@jlhoward答案的补充,其目的是自定义色阶(将显示的实际颜色)。

对于您的情况,您可能宁愿使用scale_color_manual()

scale_color_discrete()

这更快,但是取决于因子水平的顺序,这可能导致不可重复性。您可能需要指定ggplot(mtcars, aes(x=hp,color=factor(cyl)))+ geom_density()+ scale_color_discrete(name="Cylinders", labels=c("4 Cylinder","6 Cylinder","8- Cylinder")) 参数以最大程度地降低错误风险(并自定义图例中的顺序):

breaks

有关https://ggplot2-book.org/scales.html的更多信息。

相关问题