niters
niters

Reputation: 23

Why does my legend use purple for my geom_line when it should be red?

The following code produces a stacked area plot with one line graph just like I intended, however it produces a legend that doesn't match the color of the line graph. How do I fix this? Thanks!

legend on the graph

ggplot(data=revenue, aes(x=Date, alpha=0.1)) +
  geom_area(aes(y=SENSE.revenues + ORB.revenues + SENSE.refills + ORB.refills, 
                fill=" ORB Refills"),colour="Black")+
  geom_area(aes(y=SENSE.revenues + ORB.revenues + SENSE.refills, fill=" ORB 
                Revenue"),colour="Black")+
  geom_area(aes(y=SENSE.revenues + SENSE.refills, fill=" SENSE 
                Refills"),colour="Black")+
  geom_area(aes(y=SENSE.revenues, fill=" SENSE Revenues"),colour="Black") +
                labs(title="Projected Revenues", subtitle="SENSE and ORB", 
                     y="Revenue ($Thousand)") +          
  scale_fill_discrete(name="Revenue Type") +
  theme(axis.text.x = element_text(angle = 75, hjust = 1))+
  scale_x_discrete(name ="Date", limits=dates) +                   
  scale_fill_brewer(palette="Purples")+
  scale_alpha(guide = 'none')+
  theme(legend.title=element_blank())+
  geom_line(aes(y=Returns, fill=" Revenues Net of Returns"), colour="Red", 
                size=0.7)

Upvotes: 0

Views: 102

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226077

When you want to plot multiple things in a ggplot graph, it's almost always best in the long run to rearrange your data so you can plot them all at once with an aesthetic distinguishing them, rather than asking for multiple almost-identical geom_s ... here's a rough example.

Make up some data:

set.seed(101)
dd <- data.frame(Date=1:4,
                 SENSE.revenues=rpois(4,3),
                 ORB.revenues=rpois(4,3),
                 SENSE.refills=rpois(4,3),
                 ORB.refills=rpois(4,3),
                 Returns=rpois(4,3))

Convert from wide to long:

ddg <- tidyr::gather(dd[,1:5],"type","revenue",-Date)

(using dd[,1:5] leaves off the Returns; if you wanted to commit to tidyverse you could use select(-Returns) here)

Plot with a single geom_area(), distinguished by fill: use position="stack" to get all of the areas plotted one on top of the other ... plot the red line separately, with a faked colour aesthetic (we override the colour value and label with scale_colour_manual()).

ggplot(data=ddg,
       aes(x=Date,y=revenue))+
    geom_area(position="stack",aes(fill=type))+
    scale_fill_brewer(palette="Purples", name="revenue type")+
    geom_line(data=dd,aes(y=Returns,colour="junk"))+
    scale_colour_manual(values="red",
                        labels="Returns",
                        name="")

enter image description here

Upvotes: 6

Related Questions