Chp
Chp

Reputation: 105

scale_colour_discrete doesn't work when reproducing an example in R cookbook

I'm trying to reproduce an example here R Cookbook that specifies both color and shape in the legend.

The original code is

# A different data set
df2 <- data.frame(
  sex = factor(c("Female","Female","Male","Male")),
  time = factor(rep(c(1,2),2), levels=c(1,2)),
  total_bill = c(13.53, 16.81, 16.24, 17.42)
)

# A basic graph
ggplot(data=df2, aes(x=time, y=total_bill, group=sex, shape=sex)) + 
  geom_line() + 
  geom_point() +
  scale_colour_discrete(name  ="Payer",
                          breaks=c("Female", "Male"),
                          labels=c("Woman", "Man")) +
  scale_shape_discrete(name  ="Payer",
                       breaks=c("Female", "Male"),
                       labels=c("Woman", "Man"))

I don't want the line, so I commented out the part geom_line()+. The points don't have color anymore. Could anyone help with this?

# A different data set
df2 <- data.frame(
  sex = factor(c("Female","Female","Male","Male")),
  time = factor(rep(c(1,2),2), levels=c(1,2)),
  total_bill = c(13.53, 16.81, 16.24, 17.42)
)

# A basic graph
ggplot(data=df2, aes(x=time, y=total_bill, group=sex, shape=sex)) + 
#  geom_line() + 
  geom_point() +
  scale_colour_discrete(name  ="Payer",
                          breaks=c("Female", "Male"),
                          labels=c("Woman", "Man")) +
  scale_shape_discrete(name  ="Payer",
                       breaks=c("Female", "Male"),
                       labels=c("Woman", "Man"))

Upvotes: 0

Views: 731

Answers (1)

stragu
stragu

Reputation: 1291

Both of your code chunks are missing the colour aesthetic, which would be required to colour your geometries according to the categorical variable.

You can also simplify the code: using the colour aesthetic or removing the line geometry makes the group aesthetic superfluous:

# A different data set
df2 <- data.frame(
  sex = factor(c("Female","Female","Male","Male")),
  time = factor(rep(c(1,2),2), levels=c(1,2)),
  total_bill = c(13.53, 16.81, 16.24, 17.42)
)
library(ggplot2)
# A basic graph
ggplot(data=df2, aes(x=time, y=total_bill, shape=sex, colour=sex)) + 
  # geom_line() + 
  geom_point() +
  scale_colour_discrete(name  ="Payer",
                        breaks=c("Female", "Male"),
                        labels=c("Woman", "Man")) +
  scale_shape_discrete(name  ="Payer",
                       breaks=c("Female", "Male"),
                       labels=c("Woman", "Man"))

Created on 2020-12-16 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions