R:ggplot2:图例重叠不同的点形状

时间:2015-09-18 08:05:08

标签: r ggplot2

如您所见,图例在下图中重叠了不同的点形状

europe <- c(70, 67, 56, 66, 80, 75, 81, 55)
data <- data.frame(europe)

ggplot(data, aes(x=4, y=europe)) +
  labs(x = "Europe", y = NULL, title = NULL) +  
  geom_errorbar(y=data$europe, ymin=min(data$europe), ymax=max(data$europe), size=1.5, width=1, color="#7F7F7F") +
  geom_point(aes(x=4, y=data$europe[1], color="today"), size=18, shape=18) +
  geom_point(aes(x=4, y=data$europe[6], color="last week"), size=16) +
  scale_y_continuous(limits=c(50, 85), expand = c(0, 0), breaks=seq(0, 1000, 5)) +
  scale_x_continuous(limits=c(0, 8), expand = c(0, 0)) +
  scale_color_manual(name = element_blank(),
                 labels = c("today", "last week"),
                 values = c("#A50021", "#00669C"))

enter image description here

因此我尝试修复重叠失败,例如添加

+ scale_shape_manual(name = element_blank(),
                 labels = c("today", "last week"),
                 values = c(18, 16))

什么不会改变什么。当然,我的理想是一个红色圆圈和一个蓝色方块。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

通过向图例中添加不在数据中的内容,您自己会变得非常困难,因为通常图例在使用aes映射到数据时效果最佳。这就是ggplot的简易性:获取数据框中的所有内容,设置aes,如果您愿意,可以使用scale_...._manual.更改默认值

我已经添加了一个工作日&#39;变量到您的数据,以便能够正确使用aes。

#add weekday variable
data$weekday <- c("today","last week")

ggplot(data, aes(x=4, y=europe)) +
  labs(x = "Europe", y = NULL, title = NULL) +  
  geom_errorbar(aes(y=europe, ymin=min(europe), ymax=max(europe)), size=1.5, width=1, color="#7F7F7F") +
  #add subset of data here. Not that x and y were already mapped, and color, shape and size are mapped 
  #INSIDE aes
  geom_point(data=data[c(1,6),], aes(color=weekday, shape=weekday, size=weekday))+
  #manual scales
  scale_color_manual(values = c("today"="#A50021", "last week"="#00669C")) +
  scale_size_manual(values=c("today"=18, "last week"=16)) +
  scale_shape_manual(values=c("today"=20,"last week"=18))

enter image description here

删除错误栏进行编辑:

#do some reshaping/manipulating into a dataframe for plotting

plotdata <- data.frame(value=europe[c(1,6)],
                       weekday=c("today","last week"),
                       limit_value=c(min(europe),max(europe)),
                       limit_label=c("min","max"))

p2 <- ggplot(plotdata) +
  geom_point(aes(x=4,y=value,shape=weekday,colour=weekday, size=weekday))+
  scale_color_manual(values=c("today"="#A50021",
                              "last week"="#00669C"))+
  scale_size_manual(values=c("today"=18,"last week"=16))+
  scale_shape_manual(values=c("today"=18, "last week"=20))+
  geom_hline(aes(yintercept=limit_value),colour="grey",size=2)
p2

enter image description here

或者,因为时间间隔也很重要,所以你可以这样做。它使时间关系更加清晰。在我看来,min和max本身是清楚的。如果没有,您可以随时添加文本标签(或将线条设置为红色和蓝色等)。 enter image description here