cherrytree
cherrytree

Reputation: 1581

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...

enter image description here

The legend name should be 'TEST' not 'Category2'. There must be something wrong with the data in the data frame but I haven't found the culprit.

-cherrytree

Upvotes: 2

Views: 5284

Answers (2)

CPak
CPak

Reputation: 13591

You can also manually change the legend title using

p + guides(color=guide_legend(title="Whatever You Want"))

Upvotes: 1

www
www

Reputation: 39174

fill is for the interior colouring, while color is for outline. Some geom, such as geom_bar, can take both color and fill. We can change the outline of the bar using color, and the interior color using fill. However, some geom only take color, such as geom_line and geom_point, because there are no interior color to "change".

In your code, you specified the color using color=Category2. That is correct. However, you will then use scale_color_discrete(name="TEST") accordingly. 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  

Upvotes: 8

Related Questions