[英]ggplot2: unable to change title of legend
I am unable to change the legend title in this graph with this data. 我无法使用此数据来更改此图中的图例标题。
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"))
And the graph I'm creating... 我正在创建的图形...
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
Which is yielding this... 产生这个...
The legend name should be 'TEST' not 'Category2'. 图例名称应为“ TEST”而不是“ Category2”。 There must be something wrong with the data in the data frame but I haven't found the culprit. 数据框中的数据一定有问题,但我没有找到罪魁祸首。
-cherrytree -樱桃树
fill
is for the interior colouring, while color
is for outline. fill
用于内部着色,而color
用于轮廓。 Some geom
, such as geom_bar
, can take both color
and fill
. 某些geom
(例如geom_bar
)可以同时进行color
fill
。 We can change the outline of the bar using color
, and the interior color using fill
. 我们可以使用color
更改条形的轮廓,并使用fill
更改内部颜色。 However, some geom
only take color
, such as geom_line
and geom_point
, because there are no interior color to "change". 但是,某些geom
只采用color
,例如geom_line
和geom_point
,因为没有内部颜色可以“更改”。
In your code, you specified the color using color=Category2
. 在代码中,您使用color=Category2
指定了颜色。 That is correct. 那是对的。 However, you will then use scale_color_discrete(name="TEST")
accordingly. 但是,您将随后相应地使用scale_color_discrete(name="TEST")
。 The following code will work. 以下代码将起作用。
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
您还可以使用手动更改图例标题
p + guides(color=guide_legend(title="Whatever You Want"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.