Adding legend to ggplot

Hi,

I'd like to add a legend (muž, ženy) to this plot. Could you help me, please?

library(ggplot2)

pyramida2010 <-  data.frame(
  value = c(-289132,-242402,-235471,-315905,-361233,
            -393253,-476520,-435327,-359838,-345961,-349514,-370932,
            -341085,-243367,-155444,-124365,-77384,-33230,-5305,
            -1362,275413,228558,223394,300086,339507,365668,450984,
            410637,341023,333977,351237,390758,380115,293910,212293,
            196457,149630,84217,16110,5079),
  vek = as.factor(c("0-4","5-9","10-14",
                    "15-19","20-24","25-29","30-34","35-39","40-44",
                    "45-49","50-54","55-59","60-64","65-69","70-74",
                    "75-79","80-84","85-89","90-94","95-99","0-4",
                    "5-9","10-14","15-19","20-24","25-29","30-34",
                    "35-39","40-44","45-49","50-54","55-59","60-64",
                    "65-69","70-74","75-79","80-84","85-89","90-94",
                    "95-99")),
  variable = as.factor(c("muži","muži","muži",
                         "muži","muži","muži","muži","muži","muži",
                         "muži","muži","muži","muži","muži","muži","muži",
                         "muži","muži","muži","muži","ženy","ženy","ženy",
                         "ženy","ženy","ženy","ženy","ženy","ženy",
                         "ženy","ženy","ženy","ženy","ženy","ženy","ženy",
                         "ženy","ženy","ženy","ženy"))
)


cols <- c("muži"= "#254061", "ženy" = "#CD3C33")

ggplot(pyramida2010, aes(y = vek, x = value, fill = variable)) + 
  geom_bar(data=subset(pyramida2010,variable=="ženy"), stat = "identity",fill="#CD3C33") + 
  geom_bar(data=subset(pyramida2010,variable=="muži"), stat = "identity",fill="#254061") +
  theme(axis.text.x=element_blank(),
        axis.ticks=element_blank(),
        axis.title.x=element_blank(),
        axis.title.y=element_blank()
    )+
  labs(title = "Věková pyramida 2010",
       fill = "")+
  scale_colour_manual(values=cols)

image

Created on 2020-07-20 by the reprex package (v0.3.0)

You will get the legend if you do not defined the fill color within geom_bar and use scale_fill_manual. Try this:

ggplot(pyramida2010, aes(y = vek, x = value, fill = variable)) + 
  geom_bar(data=subset(pyramida2010,variable=="ženy"), stat = "identity") + 
  geom_bar(data=subset(pyramida2010,variable=="muži"), stat = "identity") +
  theme(axis.text.x=element_blank(),
        axis.ticks=element_blank(),
        axis.title.x=element_blank(),
        axis.title.y=element_blank()
  )+
  labs(title = "Věková pyramida 2010",
       fill = "")+
  scale_fill_manual(values=cols)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.