ggplot2: modify legend's elements for two factors in scatterplot {ggplot2}?

寵の児 提交于 2019-12-13 19:24:11

问题


I wish my scatter plot displays two factors: by point size and by shades of grey:

a1<-c(seq(1,10,1))
a2<-c(seq(11,20,1))
a3<-c(rep(c(1,2),each = 5))
a4<-c(rep(c(5,10,15,20,25),2))

df<-data.frame(a1,a2,a3,a4)

t1<-theme(        
  plot.background = element_blank(), 
  panel.grid.major = element_blank(), 
  panel.grid.minor = element_blank(), 
  panel.border = element_blank(), 
  panel.background = element_blank(),
  axis.line = element_line(size=.4))

ggplot(df, aes(x= a1, y= a2)) + 
  geom_point(aes(alpha=factor(a3), size = factor(a4))) + t1 + labs(x = "x label", y = "y label") +
  theme(legend.background = element_rect())

So far, more or less good.

My questions are:

  • how to remove the background in my legend? theme(legend.background = element_rect()) for some reason doesn't work...
  • how to modify both my legends headers? I imagine by this example : http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/ that is should be something like:

    scale_shape_discrete(name ="modified A4", breaks=c("1", "2"), labels = c("one","two")) but I can't figure that how to make it work?

I am sure that I am completely misunderstanding the displaying of two variables in scatter plot, but I can't find a way how to correct it?

Thank you !


回答1:


Based on suggestions of @user20650 and @inscaven and on more google search I hope to understand better how the ggplot is organized and how to produce my plot:

# dummy data
a1<-c(seq(1,10,1))
a2<-c(seq(11,20,1))
a3<-c(rep(c(1,2),each = 5))
a4<-c(rep(c(5,10,15,20,25),2))

# create data frame 
df<-data.frame(a1,a2,a3,a4)

# set nice theme  
t1<-theme(        
  plot.background = element_blank(), 
  panel.grid.major = element_blank(), 
  panel.grid.minor = element_blank(), 
  panel.border = element_blank(), 
  panel.background = element_blank(),
  axis.line = element_line(size=.4))

# create scatter plot
ggplot(df, aes(x= a1, y= a2)) +                             # create basic plot
  geom_point(aes(size = factor(a4), colour = factor(a3))) + # colour has to be inside of aes !! (ASSIGNED = MAPPED)
  scale_colour_grey(name = "Set second\nline in title") +   # change title of 1st legend, change colours 
  scale_size_discrete(name = "Name by size") +              # change title of 2nd legend, size of point has been already assigned
  theme(legend.key = element_blank()) +                     # delete grey boxes around the legend
  labs(x = "x label", y = "y label") +                      # set labels on x and y  axes
  t1                                                        # add nice theme

which results in:



来源:https://stackoverflow.com/questions/35978842/ggplot2-modify-legends-elements-for-two-factors-in-scatterplot-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!