ggplot2: Making changes to symbols in the legend

2020-03-05 03:17发布

I'm having a problem making the symbols in the legend of my plot match those in the plot itself.

Suppose the data has four columns like this

data = data.frame(x = sample(1:10, 10, replace=TRUE), y = sample(1:10, 10, replace=TRUE), 
           Rank = sample(1:10, 10, replace = TRUE), Quantified = factor(sample(1:2, 10, replace = TRUE))
)

I would like points to be different sizes (distinguished by 'Rank') and represented by different symbols (crosses and open circles, distinguished by 'Quantified').

My code is

ggplot(data, aes(x = x, y = y)) +
          geom_point(aes(size = Rank, shape = Quantified)) +
          scale_shape_manual("Quantified", labels = c("Yes", "No"), values = c(1, 4)
 )

The symbols in the plot are as I want them.

My problem is that I would like the circles in the top legend to be unfilled as they are in the plot.

I've tried a variety of commands in different parts of the code (e.g., fill = "white") but nothing seems to work quite right.

Any suggestions?

标签: r ggplot2 legend
1条回答
劳资没心,怎么记你
2楼-- · 2020-03-05 03:41

Now that I'm sure it's what you want:

library(scales)
ggplot(data, aes(x = x, y = y)) +
          geom_point(aes(size = Rank, shape = Quantified)) +
          scale_shape_manual("Quantified", labels = c("Yes", "No"), values = c(1, 4)) + 
          guides(size = guide_legend(override.aes = list(shape = 1)))

enter image description here

查看更多
登录 后发表回答