1

I use bars and line to create my plot. The demo code is:

timestamp <- seq(as.Date('2010-01-01'),as.Date('2011-12-01'),by="1 mon")
data1 <- rnorm(length(timestamp), 3000, 30)
data2 <- rnorm(length(timestamp), 30, 3)
df <- data.frame(timestamp, data1, data2)

p <- ggplot() 
p <- p + geom_histogram(data=df,aes(timestamp,data1),colour="black",stat="Identity",bindwidth=10)
p <- p + geom_line(data=df,aes(timestamp,y=data2*150),colour="red")
p <- p + scale_y_continuous(sec.axis = sec_axis(~./150, name = "data2"))
p <- p + scale_colour_manual(name="Parameter", labels=c("data1", "data2"), values = c('black', 'red'))
p <- p+ scale_shape_manual(name="Parameter",  labels=c("data1", "data2"), values = c(15,95)) 
p

This results in a plot like this:

enter image description here

This figure does not have a legend. I followed this answer to create a customized legend but it is not working in my case. I want a square and line shape in my legend corresponding to bars and line. How can we get it?

I want legend as shown in below image: enter image description here

Haroon Lone
  • 2,837
  • 5
  • 29
  • 65

1 Answers1

2

For the type of data you want to display, geom_bar is a better fit then geom_histogram. When you to manipulate the appaerance of the legend(s), you need to place the colour = ... parts inside the aes. To get the desired result it probably best to use different types of legend for the line and the bars. In that way you are better able to change the appearance of the legends with guide_legend and override.aes.

A proposal for your problem:

ggplot(data = df) + 
  geom_bar(aes(x = timestamp, y = data1, colour = "black"),
           stat = "Identity", fill = NA) +
  geom_line(aes(x = timestamp, y = data2*150, linetype = "red"), colour = "red", size = 1) +
  scale_y_continuous(sec.axis = sec_axis(~./150, name = "data2")) +
  scale_linetype_manual(labels = "data2", values = "solid") +
  scale_colour_manual(name = "Parameter\n", labels = "data1", values = "black") +
  guides(colour = guide_legend(override.aes = list(colour = "black", size = 1),
                               order = 1),
         linetype = guide_legend(title = NULL,
                                 override.aes = list(linetype = "solid",
                                                     colour = "red",
                                                     size = 1),
                                 order = 2)) +
  theme_minimal() +
  theme(legend.key = element_rect(fill = "white", colour = NA),
        legend.spacing = unit(0, "lines"))

which gives:

enter image description here

Jaap
  • 81,064
  • 34
  • 182
  • 193