0

My data is like this :

id <- c('a','a','b','b')
var <- c('Var1','Var2','Var1','Var2')
value <- c(123,421,2132,633)
df <- cbind(id,var,value)

I would like to plot a scatter plot of Var1 and a bar chart of Var2, with a legend showing that the dot is Var1 and the Bar is Var2

I have tried these code :

g <- ggplot(data = df, aes(x=id, y=value, fill=var)
g + stat_identity(geom = c("point","bar"))

But both Var1 and Var2 are showed in scatter point in this way.

I also tried to create two seprate data for Var1 and Var2.

id = c('a','b')
Var1 = c(123,2132)
Var2 = c(421,633)
df1 = cbind.data.frame(id, Var1)
df2 = cbind.data.frame(id, Var2)

g <- ggplot()
g + geom_point(data = df1, aes(x=id, y=Var1),stat = "identity")) +
    geom_bar(data = df2, aes(x=id, y=Var2),stat = "identity"))

In this way, I can combine a scatter point with a bar chart, but there is no legend and I don't know how to make the legend telling readers that the dot is Var1 and the bar is Var2

lanrete
  • 127
  • 1
  • 12
  • please use `cbind.data.frame` instead of `cbind` – bouncyball Jul 20 '16 at 16:18
  • Have you realy applied the example code that you are giving? I am asking because the both appraoches generate data of class matrix, which cannot be used directlyin ggplot. Also, the ggplot in the second approach does not work, because you close to many brackets. Lastly, have you checked other threads on SO, such as [this](http://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-line-plot) one – Daniel Jul 20 '16 at 16:23
  • indeed i don't think you can do it without splitting the data (outside or inside ggplot) – agenis Jul 20 '16 at 16:24

1 Answers1

1

First off, see this post. Thanks @Daniel!

You could try this:

id = c('a','b')
Var1 = c(123,2132)
Var2 = c(421,633)
df1 = cbind.data.frame(id, Var1)
df2 = cbind.data.frame(id, Var2)
library(ggplot2)
g <- ggplot()
g + geom_bar(data = df2, aes(x=id, y=Var2, fill = 'Var2'),stat = "identity")+
     geom_point(data = df1, aes(x=id, y=Var1, colour = 'Var1'),stat = "identity", size = 2) +
    scale_fill_manual(values = c('Var2' = 'blue'), name = 'Bars')+
    scale_colour_manual(values = c('Var1' = 'red'), name = 'Dots')

enter image description here

Basically, we use the aes within geom_point and geom_bar to define our color or fill. Then use scale_*_manual to control display. Also, we call geom_bar before geom_point so that the dots are plotted over the bar. Also, I use size = 2 in geom_point so that the point is a little more distinguishable.

Community
  • 1
  • 1
bouncyball
  • 10,631
  • 19
  • 31
  • 1
    I would just add the link to [this](http://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-line-plot) question, where different variants are explained for a line plot. – Daniel Jul 20 '16 at 16:26