ggplot2:无法更改图例的标题

che*_*ree 1 r ggplot2

我无法使用此数据来更改此图中的图例标题。

df <- structure(list(year = structure(c(1L, 1L, 2L, 2L, 2L, 3L, 3L, 
3L), .Label = c("2015", "2016", "2017"), class = "factor"), Category2 = c("grower", 
"starter", "grower", "layer", "starter", "grower", "layer", "starter"
), per_pound = c(0.2072, 0.382, 0.172, 0.173, 0.3705, 0.178667, 
0.1736, 0.277375)), .Names = c("year", "Category2", "per_pound"
), row.names = c(NA, -8L), vars = "year", drop = TRUE, class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))
Run Code Online (Sandbox Code Playgroud)

我正在创建的图形...

library (ggplot2)
p <- ggplot (data=df, aes(x=year, y=per_pound, group=Category2, color=Category2)) + geom_line() + geom_point()
p <- p + scale_fill_discrete(name="TEST")
p
Run Code Online (Sandbox Code Playgroud)

产生这个...

在此处输入图片说明

图例名称应为“ TEST”而不是“ Category2”。数据框中的数据一定有问题,但我没有找到罪魁祸首。

-樱桃树

www*_*www 5

fill用于内部着色,而color用于轮廓。有的geom,比如geom_bar,可以采取两个colorfill。我们可以使用更改条形的轮廓,使用更改color内部颜色fill。但是,某些geom仅取color,例如geom_linegeom_point,因为没有内部颜色可以“更改”。

在代码中,您使用指定了颜色color=Category2。那是正确的。但是,您将随后相应地使用scale_color_discrete(name="TEST")。以下代码将起作用。

library (ggplot2)
p <- ggplot (data=df, aes(x=year, y=per_pound, group=Category2, color=Category2)) + geom_line() + geom_point()
p <- p + scale_color_discrete(name="TEST")
p  
Run Code Online (Sandbox Code Playgroud)